from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import Session, select

from app.api.deps import get_session
from app.models.core import ContentPillar, CreativeBrief, HashtagSet, HookTemplate, Series, Theme

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

@router.get("")
def list_themes(platform: str | None=None, language: str | None=None, session: Session=Depends(get_session)):
    items=session.exec(select(Theme).where(Theme.status!="archived")).all()
    return {"items":[t.model_dump(mode="json") for t in items]}

@router.post("")
def create_theme(payload: dict, session: Session=Depends(get_session)):
    theme=Theme(**payload); session.add(theme); session.commit(); session.refresh(theme); return theme.model_dump(mode="json")

@router.get("/recommend")
def recommend(platform: str="tiktok", language: str="en", session: Session=Depends(get_session)):
    theme=session.exec(select(Theme).where(Theme.default_language==language, Theme.status=="active").order_by(Theme.performance_score.desc())).first()
    return {"platform": platform, "theme": theme.model_dump(mode="json") if theme else None}

@router.get("/{theme_id}")
def get_theme(theme_id: str, session: Session=Depends(get_session)):
    theme=session.get(Theme, theme_id)
    if not theme: raise HTTPException(404,"Theme not found")
    return theme.model_dump(mode="json")

@router.patch("/{theme_id}")
def patch_theme(theme_id: str, payload: dict, session: Session=Depends(get_session)):
    theme=session.get(Theme, theme_id)
    if not theme: raise HTTPException(404,"Theme not found")
    for k,v in payload.items():
        if hasattr(theme,k): setattr(theme,k,v)
    session.add(theme); session.commit(); session.refresh(theme); return theme.model_dump(mode="json")

@router.delete("/{theme_id}")
def archive_theme(theme_id: str, session: Session=Depends(get_session)):
    theme=session.get(Theme, theme_id)
    if not theme: raise HTTPException(404,"Theme not found")
    theme.status="archived"; session.add(theme); session.commit(); return {"ok": True}

@router.post("/{theme_id}/performance-feedback")
def feedback(theme_id: str, payload: dict, session: Session=Depends(get_session)):
    theme=session.get(Theme, theme_id)
    if not theme: raise HTTPException(404,"Theme not found")
    theme.performance_score=float(payload.get("performance_score", theme.performance_score)); session.add(theme); session.commit()
    return {"ok": True, "performance_score": theme.performance_score}
