from __future__ import annotations

from pathlib import Path

from fastapi import APIRouter, HTTPException, Request

from ..chat.session import ChatSessionManager

router = APIRouter()


@router.get("/api/sessions")
async def list_sessions(request: Request) -> dict[str, object]:
    session_manager: ChatSessionManager = request.app.state.session_manager
    session_manager.cleanup_dead_sessions()
    return {"sessions": session_manager.list_sessions()}


@router.post("/api/sessions")
async def create_session(request: Request, data: dict[str, object]) -> dict[str, object]:
    session_manager: ChatSessionManager = request.app.state.session_manager
    name = data.get("name")
    project_path = data.get("project_path", str(Path.cwd()))
    resume = data.get("resume")
    claude_args = data.get("claude_args")
    rows = data.get("rows")
    cols = data.get("cols")

    resume_option: str | bool | None = None
    if resume is True:
        resume_option = True
    elif isinstance(resume, str) and resume:
        resume_option = resume

    try:
        session = await session_manager.create_session(
            name=str(name) if name else None,
            project_path=str(project_path),
            resume=resume_option,
            claude_args=(
                [str(a) for a in claude_args] if isinstance(claude_args, list) else None
            ),
            initial_rows=int(rows) if isinstance(rows, (int, float, str)) else None,
            initial_cols=int(cols) if isinstance(cols, (int, float, str)) else None,
        )
        return {"status": "ok", "session": session.to_dict()}
    except (OSError, ValueError, RuntimeError) as e:
        raise HTTPException(status_code=500, detail=str(e)) from e


@router.get("/api/sessions/{session_id}")
async def get_session(request: Request, session_id: str) -> dict[str, object]:
    session_manager: ChatSessionManager = request.app.state.session_manager
    session = session_manager.get_session(session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Session not found")
    return session.to_dict()


@router.post("/api/sessions/{session_id}/prompt")
async def send_session_prompt(
    request: Request, session_id: str, data: dict[str, str]
) -> dict[str, str]:
    session_manager: ChatSessionManager = request.app.state.session_manager
    session = session_manager.get_session(session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Session not found")

    if not session.is_alive():
        raise HTTPException(status_code=400, detail="Session is not running")

    prompt = data.get("prompt", "")
    if not prompt:
        raise HTTPException(status_code=400, detail="Prompt is required")

    await session.send_prompt(prompt, source="web")
    return {"status": "ok"}


@router.post("/api/sessions/{session_id}/input")
async def send_session_input(
    request: Request, session_id: str, data: dict[str, str]
) -> dict[str, str]:
    session_manager: ChatSessionManager = request.app.state.session_manager
    session = session_manager.get_session(session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Session not found")

    if not session.is_alive():
        raise HTTPException(status_code=400, detail="Session is not running")

    input_data = data.get("data", "")
    if not input_data:
        raise HTTPException(status_code=400, detail="Data is required")

    await session.send_input(input_data.encode("utf-8"), source="web")
    return {"status": "ok"}


@router.delete("/api/sessions/{session_id}")
async def stop_session(request: Request, session_id: str) -> dict[str, str]:
    session_manager: ChatSessionManager = request.app.state.session_manager
    success = await session_manager.stop_session(session_id)
    if not success:
        raise HTTPException(status_code=404, detail="Session not found")
    return {"status": "ok"}

