from datetime import date

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app import models, schemas
from app.database import get_db
from app.services.task_runner import TaskRunner

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


@router.get("", response_model=list[schemas.FeishuSessionRead])
def list_sessions(db: Session = Depends(get_db)) -> list[models.FeishuSession]:
    return db.query(models.FeishuSession).order_by(models.FeishuSession.created_at.desc()).all()


@router.get("/{session_id}", response_model=schemas.FeishuSessionRead)
def get_session(session_id: int, db: Session = Depends(get_db)) -> models.FeishuSession:
    session = db.get(models.FeishuSession, session_id)
    if not session:
        raise HTTPException(status_code=404, detail="场次不存在")
    return session


@router.post("", response_model=schemas.FeishuSessionRead)
def create_session(payload: schemas.FeishuSessionCreate, db: Session = Depends(get_db)) -> models.FeishuSession:
    next_id = db.query(models.FeishuSession).count() + 1
    session = models.FeishuSession(
        session_code=payload.session_code or f"MANUAL-{next_id:04d}",
        title=payload.title,
        date=payload.date or date.today(),
        teachers=payload.teachers,
        feishu_doc_url=payload.feishu_doc_url,
        feishu_record_id=payload.feishu_record_id,
        source_file_name=payload.source_file_name,
        source_text=payload.source_text,
        process_status=models.ProcessStatus.unprocessed,
    )
    db.add(session)
    db.commit()
    db.refresh(session)
    return session


@router.patch("/{session_id}", response_model=schemas.FeishuSessionRead)
def update_session(
    session_id: int, payload: schemas.FeishuSessionUpdate, db: Session = Depends(get_db)
) -> models.FeishuSession:
    session = db.get(models.FeishuSession, session_id)
    if not session:
        raise HTTPException(status_code=404, detail="场次不存在")
    for key, value in payload.model_dump(exclude_unset=True).items():
        setattr(session, key, value)
    db.commit()
    db.refresh(session)
    return session


@router.post("/{session_id}/process", response_model=schemas.TaskRunRead)
async def process_session(session_id: int, db: Session = Depends(get_db)) -> models.TaskRun:
    runner = TaskRunner()
    task = await runner.run(db, task_type=models.TaskType.manual_process, session_id=session_id)
    return task


@router.post("/{session_id}/reprocess", response_model=schemas.TaskRunRead)
async def reprocess_session(session_id: int, db: Session = Depends(get_db)) -> models.TaskRun:
    runner = TaskRunner()
    task = await runner.run(db, task_type=models.TaskType.manual_process, session_id=session_id, reprocess=True)
    return task

