from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from agent.chat_agent import ChatAgent
from database import get_db
from memory.session_store import SessionStore
from models.schemas import (
    ChatRequest,
    ChatResponse,
    MessageOut,
    SessionCreate,
    SessionOut,
)

router = APIRouter(prefix="/sessions", tags=["sessions"])


@router.get("", response_model=list[SessionOut])
def list_sessions(db: Session = Depends(get_db)):
    store = SessionStore(db)
    return store.list_sessions()


@router.post("", response_model=SessionOut)
def create_session(body: SessionCreate, db: Session = Depends(get_db)):
    store = SessionStore(db)
    return store.create_session(body.title)


@router.get("/{session_id}", response_model=SessionOut)
def get_session(session_id: str, db: Session = Depends(get_db)):
    store = SessionStore(db)
    session = store.get_session(session_id)
    if not session:
        raise HTTPException(status_code=404, detail="会话不存在")
    return session


@router.delete("/{session_id}")
def delete_session(session_id: str, db: Session = Depends(get_db)):
    store = SessionStore(db)
    if not store.delete_session(session_id):
        raise HTTPException(status_code=404, detail="会话不存在")
    return {"ok": True}


@router.get("/{session_id}/messages", response_model=list[MessageOut])
def get_messages(session_id: str, db: Session = Depends(get_db)):
    store = SessionStore(db)
    if not store.get_session(session_id):
        raise HTTPException(status_code=404, detail="会话不存在")
    return store.get_messages(session_id)


@router.post("/{session_id}/chat", response_model=ChatResponse)
async def chat(session_id: str, body: ChatRequest, db: Session = Depends(get_db)):
    agent = ChatAgent(db)
    try:
        user_id, assistant_id, content = await agent.reply(
            session_id, body.message.strip()
        )
    except LookupError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    except RuntimeError as exc:
        raise HTTPException(status_code=500, detail=str(exc)) from exc
    except Exception as exc:
        raise HTTPException(status_code=502, detail=f"DeepSeek 请求失败: {exc}") from exc

    store = SessionStore(db)
    user_msg = store.get_messages(session_id)
    user_message = next(m for m in user_msg if m.id == user_id)
    assistant_message = next(m for m in user_msg if m.id == assistant_id)
    return ChatResponse(
        user_message=MessageOut.model_validate(user_message),
        assistant_message=MessageOut.model_validate(assistant_message),
    )
