from sqlalchemy import select
from sqlalchemy.orm import Session

from app.db.models import Report
from app.mock_data import MOCK_MOVEMENT_REPORT
from app.services.videos import verify_child_owner


RISK_LABELS = {
    "low": "正常",
    "medium": "中度关注",
    "high": "高度关注",
    "review_required": "建议复核",
}

METRIC_LEVEL_LABELS = {
    "medium": "中度",
    "low": "轻度",
    "normal": "正常",
    "high": "重度",
}


def report_to_dict(report: Report) -> dict:
    if report.report_type == "movement_scoring" and report.metrics:
        stored = report.metrics[0] if isinstance(report.metrics, list) else report.metrics
        if isinstance(stored, dict) and "score" in stored:
            return stored
        return {**MOCK_MOVEMENT_REPORT, "id": report.id, "childId": report.child_id, "taskId": report.task_id}

    return {
        "id": report.id,
        "childId": report.child_id,
        "taskId": report.task_id,
        "riskLevel": report.risk_level,
        "summary": report.summary,
        "metrics": report.metrics,
        "recommendations": report.recommendations,
        "disclaimer": report.disclaimer,
        "status": report.status,
        "reviewedBy": report.reviewed_by,
    }


def get_report_for_user(db: Session, user_id: int, report_id: int) -> Report | None:
    report = db.get(Report, report_id)
    if not report:
        return None
    if not verify_child_owner(db, user_id, report.child_id):
        return None
    return report


def list_reports_for_child(
    db: Session, user_id: int, child_id: int, limit: int = 10
) -> list[Report] | None:
    if not verify_child_owner(db, user_id, child_id):
        return None
    return list(
        db.scalars(
            select(Report)
            .where(Report.child_id == child_id)
            .order_by(Report.id.desc())
            .limit(limit)
        ).all()
    )
