# backend/app/services/classification.py
import uuid

from sqlmodel import Session, select

from ..llm.provider import Classification, LLMProvider
from ..models import InboxClassification, Project


def _context(s: Session) -> dict:
    projects = s.exec(select(Project)).all()
    return {"projects": [{"id": p.id, "name": p.name, "folder_id": p.folder_id} for p in projects]}


def classify(
    s: Session, raw: str, provider: LLMProvider, force_type: str | None = None
) -> Classification:
    # provider 는 라우터에서 Depends(get_provider) 로 주입받아 전달한다(auto: ollama→heuristic).
    c = provider.classify_capture(raw, _context(s))
    if force_type and force_type in ("task", "event", "idea"):
        c.type = force_type  # 사용자 강제 타입
        c.reason = f"사용자가 '{force_type}'(으)로 지정했어요. " + c.reason
    return c


def persist_classification(
    s: Session, inbox_item_id: str, c: Classification
) -> InboxClassification:
    row = InboxClassification(
        id="cls-" + uuid.uuid4().hex[:8],  # TEXT PK
        inbox_item_id=inbox_item_id,
        type=c.type,
        sphere=c.sphere,
        project_id=c.project_id,
        proj_label=c.proj_label,
        tone=c.tone,
        due_text=c.due_text,
        when_text=c.when_text,
        extra=c.extra,
        reason=c.reason,
        confidence=c.confidence,
        model=c.model,
    )
    s.add(row)
    s.commit()
    s.refresh(row)
    return row
