from fastapi import APIRouter, Depends, Response
from sqlalchemy.orm import Session
from sqlalchemy import func

from app.core.database import get_db
from app.models.user import User
from app.models.project import ClassificationResult, ClassificationProject
from app.models.classification import Category, DataLevel
from app.schemas.common import ResponseModel
from app.api.deps import get_current_user, require_guest_or_above
from app.services import report_service

router = APIRouter()


@router.get("/stats")
def get_report_stats(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_guest_or_above),
):
    """Global report statistics."""
    total = db.query(ClassificationResult).count()
    auto = db.query(ClassificationResult).filter(ClassificationResult.source == 'auto').count()
    manual = db.query(ClassificationResult).filter(ClassificationResult.source == 'manual').count()
    reviewed = db.query(ClassificationResult).filter(ClassificationResult.status == 'reviewed').count()

    # Level distribution
    level_dist = db.query(DataLevel.name, DataLevel.code, func.count(ClassificationResult.id)).\
        join(ClassificationResult, DataLevel.id == ClassificationResult.level_id).\
        group_by(DataLevel.id).order_by(DataLevel.sort_order).all()

    return ResponseModel(data={
        "total": total,
        "auto": auto,
        "manual": manual,
        "reviewed": reviewed,
        "level_distribution": [
            {"name": name, "code": code, "count": count}
            for name, code, count in level_dist
        ],
    })


@router.get("/projects/{project_id}/download")
def download_report(
    project_id: int,
    format: str = "docx",
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    if format == "excel":
        content = report_service.generate_excel_report(db, project_id)
        return Response(
            content=content,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            headers={"Content-Disposition": f"attachment; filename=report_project_{project_id}.xlsx"},
        )
    content = report_service.generate_classification_report(db, project_id)
    return Response(
        content=content,
        media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        headers={"Content-Disposition": f"attachment; filename=report_project_{project_id}.docx"},
    )


@router.get("/projects/{project_id}/summary")
def report_summary(
    project_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    data = report_service.get_report_summary(db, project_id)
    return ResponseModel(data=data)
