from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app import models, schemas
from app.config import get_settings
from app.database import get_db

router = APIRouter(prefix="/settings", tags=["settings"])

SENSITIVE_MARKERS = {"secret", "token", "key", "password", "api_key"}


@router.get("", response_model=schemas.SafeSettingsRead)
def read_settings(db: Session = Depends(get_db)) -> schemas.SafeSettingsRead:
    settings = get_settings()
    rows = db.query(models.SystemSetting).order_by(models.SystemSetting.key.asc()).all()
    driver = settings.resolved_database_url.split(":", 1)[0]
    return schemas.SafeSettingsRead(
        feishu_configured=settings.feishu_configured,
        openai_configured=settings.openai_configured,
        model_name=settings.model_name,
        schedule_cron=settings.schedule_cron,
        schedule_timezone=settings.schedule_timezone,
        mock_mode=settings.mock_mode or not settings.feishu_configured,
        database_url=f"{driver}://***",
        feishu_tables_configured={
            "session": bool(settings.feishu_table_id_session),
            "raw_qa": bool(settings.feishu_table_id_raw_qa),
            "standard_qa": bool(settings.feishu_table_id_standard_qa),
        },
        system_settings=[
            {"key": row.key, "value": row.value, "description": row.description, "updated_at": row.updated_at}
            for row in rows
        ],
    )


@router.patch("", response_model=schemas.SafeSettingsRead)
def patch_settings(payload: schemas.SettingsPatch, db: Session = Depends(get_db)) -> schemas.SafeSettingsRead:
    for key, value in payload.settings.items():
        lower = key.lower()
        if any(marker in lower for marker in SENSITIVE_MARKERS):
            raise HTTPException(status_code=400, detail="敏感密钥不能写入 system_settings，请使用 .env")
        row = db.query(models.SystemSetting).filter(models.SystemSetting.key == key).first()
        if row:
            row.value = value
        else:
            db.add(models.SystemSetting(key=key, value=value, description="后台页面写入的非敏感配置"))
    db.commit()
    return read_settings(db)

