"""Experience case API router (basic CRUD for Phase 2)."""
import json
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from ..database import get_db
from ..models.experience_case import ExperienceCase

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


def _case_to_dict(case: ExperienceCase) -> dict:
    return {
        "id": case.id,
        "source_plan_id": case.source_plan_id or "",
        "topology": case.topology or "SSSR",
        "model_path": case.model_path or "",
        "params": case.get_params(),
        "metrics": case.get_metrics(),
        "conclusion": case.conclusion or "",
        "tags": [t.strip() for t in (case.tags or "").split(",") if t.strip()],
        "rating": case.rating or 0,
        "created_at": case.created_at,
    }


@router.get("")
def list_experience(
    topology: str | None = None,
    tag: str | None = None,
    skip: int = 0,
    limit: int = 50,
    db: Session = Depends(get_db),
):
    """List experience cases with filters."""
    query = db.query(ExperienceCase)
    if topology:
        query = query.filter(ExperienceCase.topology == topology)
    if tag:
        query = query.filter(ExperienceCase.tags.contains(tag))
    total = query.count()
    cases = query.order_by(ExperienceCase.created_at.desc()).offset(skip).limit(limit).all()
    return {"total": total, "items": [_case_to_dict(c) for c in cases]}


@router.post("", status_code=201)
def create_experience(
    data: dict,
    db: Session = Depends(get_db),
):
    """Create an experience case from a dict."""
    case = ExperienceCase(
        source_plan_id=data.get("source_plan_id", ""),
        topology=data.get("topology", "SSSR"),
        model_path=data.get("model_path", ""),
        conclusion=data.get("conclusion", ""),
        tags=",".join(data.get("tags", [])),
        rating=data.get("rating", 0),
    )
    case.params_json = json.dumps(data.get("params", {}), ensure_ascii=False)
    case.metrics_json = json.dumps(data.get("metrics", {}), ensure_ascii=False)
    db.add(case)
    db.commit()
    db.refresh(case)
    return _case_to_dict(case)


@router.get("/{case_id}")
def get_experience(case_id: int, db: Session = Depends(get_db)):
    """Get an experience case by ID."""
    case = db.query(ExperienceCase).filter(ExperienceCase.id == case_id).first()
    if not case:
        raise HTTPException(status_code=404, detail="Experience case not found")
    return _case_to_dict(case)


@router.delete("/{case_id}", status_code=204)
def delete_experience(case_id: int, db: Session = Depends(get_db)):
    """Delete an experience case."""
    case = db.query(ExperienceCase).filter(ExperienceCase.id == case_id).first()
    if not case:
        raise HTTPException(status_code=404, detail="Experience case not found")
    db.delete(case)
    db.commit()
    return None
