from typing import List

from fastapi import APIRouter, HTTPException

from nexus_agent.core.session_manager import session_manager
from nexus_agent.models.session import (
    CreateSessionRequest,
    SaveMessagesRequest,
    SessionDetail,
    SessionInfo,
    UpdateSessionRequest,
)

router = APIRouter()


@router.get("/", response_model=List[SessionInfo])
async def list_sessions():
    return session_manager.get_all()


@router.post("/", response_model=SessionInfo)
async def create_session(req: CreateSessionRequest):
    return session_manager.create_session(req.title)


@router.get("/{session_id}", response_model=SessionDetail)
async def get_session(session_id: str):
    info = session_manager.get_session(session_id)
    if not info:
        raise HTTPException(status_code=404, detail="Session not found")
    messages = session_manager.get_messages(session_id) or []
    return SessionDetail(info=info, messages=messages)


@router.put("/{session_id}/messages", response_model=SessionInfo)
async def save_messages(session_id: str, req: SaveMessagesRequest):
    result = session_manager.save_messages(session_id, req.messages)
    if not result:
        raise HTTPException(status_code=404, detail="Session not found")
    return result


@router.patch("/{session_id}", response_model=SessionInfo)
async def update_session(session_id: str, req: UpdateSessionRequest):
    result = session_manager.update_session(session_id, req.title)
    if not result:
        raise HTTPException(status_code=404, detail="Session not found")
    return result


@router.delete("/{session_id}")
async def delete_session(session_id: str):
    if not session_manager.delete_session(session_id):
        raise HTTPException(status_code=404, detail="Session not found")
    return {"status": "deleted"}
