from __future__ import annotations

from sqlalchemy import select
from sqlalchemy.orm import Session

from app.models.system_model_setting import SystemModelSetting
from app.models.system_setting import SystemSetting
from app.models.system_setting_secret import SystemSettingSecret

SETTINGS_ROW_ID = "default"


class SettingsRepository:
    def __init__(self, db: Session) -> None:
        self.db = db

    def get_settings(self) -> SystemSetting | None:
        stmt = select(SystemSetting).where(SystemSetting.id == SETTINGS_ROW_ID)
        return self.db.execute(stmt).scalars().first()

    def get_secrets(self) -> SystemSettingSecret | None:
        stmt = select(SystemSettingSecret).where(SystemSettingSecret.id == SETTINGS_ROW_ID)
        return self.db.execute(stmt).scalars().first()

    def get_model_settings(self) -> list[SystemModelSetting]:
        stmt = select(SystemModelSetting)
        return list(self.db.execute(stmt).scalars().all())

    def get_model_setting(self, slot: str) -> SystemModelSetting | None:
        stmt = select(SystemModelSetting).where(SystemModelSetting.slot == slot)
        return self.db.execute(stmt).scalars().first()

    def save_settings(self, settings: SystemSetting) -> SystemSetting:
        self.db.add(settings)
        self.db.commit()
        self.db.refresh(settings)
        return settings

    def save_secrets(self, secrets: SystemSettingSecret) -> SystemSettingSecret:
        self.db.add(secrets)
        self.db.commit()
        self.db.refresh(secrets)
        return secrets
