# parametros.py
from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from sqlalchemy.ext.asyncio import AsyncSession
from database import get_session
from models import AliquotaUF, ParametrosFormula, SelicMensal
from typing import List
from pydantic import BaseModel
import datetime

router = APIRouter()

# === Schemas ===
class AliquotaUFSchema(BaseModel):
    uf: str
    exercicio: int
    aliquota: float

    class Config:
        orm_mode = True

class ParametrosFormulaSchema(BaseModel):
    nome: str
    formula: str
    campos: str

    class Config:
        orm_mode = True

class SelicMensalSchema(BaseModel):
    mes: str  # 'YYYY-MM'
    fator: float

    class Config:
        orm_mode = True

# === Rotas ===

@router.get("/parametros/aliquotas", response_model=List[AliquotaUFSchema])
def listar_aliquotas(db: AsyncSession = Depends(get_session)):
    return db.query(AliquotaUF).all()

@router.post("/parametros/aliquotas")
def adicionar_aliquota(aliq: AliquotaUFSchema, db: AsyncSession = Depends(get_session)):
    existente = db.query(AliquotaUF).filter_by(uf=aliq.uf, exercicio=aliq.exercicio).first()
    if existente:
        existente.aliquota = aliq.aliquota
    else:
        novo = AliquotaUF(**aliq.dict())
        db.add(novo)
    db.commit()
    return {"status": "ok"}

@router.get("/parametros/formulas", response_model=List[ParametrosFormulaSchema])
def listar_formulas(db: AsyncSession = Depends(get_session)):
    return db.query(ParametrosFormula).all()

@router.post("/parametros/formulas")
def salvar_formula(form: ParametrosFormulaSchema, db: AsyncSession = Depends(get_session)):
    existente = db.query(ParametrosFormula).filter_by(nome=form.nome).first()
    if existente:
        existente.formula = form.formula
        existente.campos = form.campos
    else:
        novo = ParametrosFormula(**form.dict())
        db.add(novo)
    db.commit()
    return {"status": "ok"}

@router.get("/parametros/selic", response_model=List[SelicMensalSchema])
def listar_selic(db: AsyncSession = Depends(get_session)):
    return db.query(SelicMensal).order_by(SelicMensal.mes.desc()).all()

@router.post("/parametros/selic")
def salvar_selic(selic: SelicMensalSchema, db: AsyncSession = Depends(get_session)):
    existente = db.query(SelicMensal).filter_by(mes=selic.mes).first()
    if existente:
        existente.fator = selic.fator
    else:
        novo = SelicMensal(**selic.dict())
        db.add(novo)
    db.commit()
    return {"status": "ok"}
