from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from pydantic import BaseModel

from app.db.database import get_db
from app.db.models import ApiSettings
from app.services.kis_auth import kis_auth

router = APIRouter()

class SettingsSchema(BaseModel):
    # Partial schema for updates
    appKey: str | None = None
    appSecret: str | None = None
    accountNumber: str | None = None
    kisApiDelayMs: int | None = None
    
    class Config:
        from_attributes = True

@router.get("/", response_model=SettingsSchema)
async def get_settings(db: AsyncSession = Depends(get_db)):
    stmt = select(ApiSettings).where(ApiSettings.id == 1)
    result = await db.execute(stmt)
    settings = result.scalar_one_or_none()
    if not settings:
        raise HTTPException(status_code=404, detail="Settings not initialized")
    return settings

@router.put("/", response_model=SettingsSchema)
async def update_settings(payload: SettingsSchema, db: AsyncSession = Depends(get_db)):
    stmt = select(ApiSettings).where(ApiSettings.id == 1)
    result = await db.execute(stmt)
    settings = result.scalar_one_or_none()
    
    if not settings:
        settings = ApiSettings(id=1)
        db.add(settings)
    
    # Update fields if provided
    if payload.appKey is not None: settings.appKey = payload.appKey
    if payload.appSecret is not None: settings.appSecret = payload.appSecret
    if payload.accountNumber is not None: settings.accountNumber = payload.accountNumber
    if payload.kisApiDelayMs is not None: settings.kisApiDelayMs = payload.kisApiDelayMs
    
    await db.commit()
    await db.refresh(settings)

    # Trigger Token Refresh if Creds changed (Async Background task ideally)
    # await kis_auth.get_access_token(db) 
    
    return settings
