"""Questions API routes for reading and saving per-stage question JSON files."""

from __future__ import annotations

import json

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel

from mixersystem.studio.config import StudioConfig
from mixersystem.studio.routes import get_config
from mixersystem.studio.scanner import WORKFLOW_STAGES
from mixersystem.studio.session_paths import resolve_session_path

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

_VALID_STAGES = set(WORKFLOW_STAGES)


class QuestionItem(BaseModel):
    id: str
    text: str
    answer: str | None = None
    auto_respond: bool = False
    reaction: str | None = None
    inactive: bool = False
    implemented: bool = False


class SaveQuestionsBody(BaseModel):
    questions: list[QuestionItem]


def _resolve_folder_or_400(config: StudioConfig, folder_name: str):
    try:
        return resolve_session_path(config.sessions_dir, folder_name)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e)) from e


def _split_folder_and_stage(path: str) -> tuple[str, str]:
    """Split 'parent/child/task' into ('parent/child', 'task')."""
    parts = path.rsplit("/", 1)
    if len(parts) != 2:
        raise HTTPException(status_code=400, detail="Invalid path")
    return parts[0], parts[1]


@router.get("/{path:path}")
def get_questions(path: str, config: StudioConfig = Depends(get_config)):
    folder_name, stage = _split_folder_and_stage(path)
    if stage not in _VALID_STAGES:
        raise HTTPException(status_code=400, detail=f"Invalid stage '{stage}'")

    folder = _resolve_folder_or_400(config, folder_name)
    if not folder.is_dir():
        raise HTTPException(status_code=404, detail=f"Session folder '{folder_name}' not found")

    qpath = folder / f"{stage}_questions.json"
    if not qpath.is_file():
        return {"questions": []}

    try:
        data = json.loads(qpath.read_text())
        return {"questions": data.get("questions", [])}
    except (json.JSONDecodeError, OSError):
        return {"questions": []}


@router.put("/{path:path}")
def save_questions(path: str, body: SaveQuestionsBody, config: StudioConfig = Depends(get_config)):
    folder_name, stage = _split_folder_and_stage(path)
    if stage not in _VALID_STAGES:
        raise HTTPException(status_code=400, detail=f"Invalid stage '{stage}'")

    folder = _resolve_folder_or_400(config, folder_name)
    if not folder.is_dir():
        raise HTTPException(status_code=404, detail=f"Session folder '{folder_name}' not found")

    qpath = folder / f"{stage}_questions.json"
    data = {"questions": [q.model_dump() for q in body.questions]}
    qpath.write_text(json.dumps(data, indent=2) + "\n")

    return {"stage": stage, "saved": True}
