"""
routers/dashboard_router.py
------------------------------
Aggregate research statistics and anonymized CSV export.

Privacy note: exports use `participant_code` (a random research ID), never
email or display_name, and never raw message text — only aggregate scores.
This endpoint would need an is_researcher/is_admin role check added before
any real deployment; see the TODO below.
"""

import csv
import io
from collections import defaultdict
from datetime import datetime, timedelta, timezone

from fastapi import APIRouter, Depends
from fastapi.responses import StreamingResponse
from sqlalchemy.orm import Session

from .. import db_models, schemas
from ..auth import get_current_user
from ..database import get_db

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

# TODO(security): before production use, restrict these endpoints to users
# with a researcher/admin role (e.g. an `is_researcher` column on User),
# rather than any authenticated user. Left open here so the endpoint is
# testable without building a full role system in this stage.


@router.get("/stats", response_model=schemas.DashboardStats)
def get_stats(db: Session = Depends(get_db), _current_user=Depends(get_current_user)):
    total_participants = db.query(db_models.User).count()
    total_sessions = db.query(db_models.ChatSession).count()
    completed_sessions = (
        db.query(db_models.ChatSession)
        .filter(db_models.ChatSession.stage == "complete")
        .count()
    )

    predictions = db.query(db_models.AIPrediction).all()
    n = len(predictions) or 1
    avg_dep = sum(float(p.depression_score) for p in predictions) / n
    avg_anx = sum(float(p.anxiety_score) for p in predictions) / n
    avg_stress = sum(float(p.stress_score) for p in predictions) / n
    avg_wellness = sum(float(p.overall_wellness_score) for p in predictions) / n

    risk_distribution = {
        "depression": defaultdict(int),
        "anxiety": defaultdict(int),
        "stress": defaultdict(int),
    }
    for p in predictions:
        risk_distribution["depression"][p.depression_risk_level] += 1
        risk_distribution["anxiety"][p.anxiety_risk_level] += 1
        risk_distribution["stress"][p.stress_risk_level] += 1

    for domain in risk_distribution:
        for level in ("Low", "Moderate", "High"):
            risk_distribution[domain].setdefault(level, 0)

    # Sessions in the last 7 days, by date
    now = datetime.now(timezone.utc)
    daily = defaultdict(int)
    for i in range(7):
        day = (now - timedelta(days=i)).strftime("%Y-%m-%d")
        daily[day] = 0
    sessions = db.query(db_models.ChatSession).filter(
        db_models.ChatSession.started_at >= now - timedelta(days=7)
    ).all()
    for s in sessions:
        day = s.started_at.strftime("%Y-%m-%d")
        if day in daily:
            daily[day] += 1

    # Sessions in the last 12 months, by month
    monthly = defaultdict(int)
    for i in range(12):
        month = (now - timedelta(days=30 * i)).strftime("%Y-%m")
        monthly[month] = 0
    sessions_12mo = db.query(db_models.ChatSession).filter(
        db_models.ChatSession.started_at >= now - timedelta(days=365)
    ).all()
    for s in sessions_12mo:
        month = s.started_at.strftime("%Y-%m")
        if month in monthly:
            monthly[month] += 1

    return schemas.DashboardStats(
        total_participants=total_participants,
        total_sessions=total_sessions,
        completed_sessions=completed_sessions,
        average_depression_score=round(avg_dep, 1),
        average_anxiety_score=round(avg_anx, 1),
        average_stress_score=round(avg_stress, 1),
        average_wellness_score=round(avg_wellness, 1),
        risk_distribution={k: dict(v) for k, v in risk_distribution.items()},
        sessions_last_7_days=dict(sorted(daily.items())),
        sessions_last_12_months=dict(sorted(monthly.items())),
    )


@router.get("/export-csv")
def export_csv(db: Session = Depends(get_db), _current_user=Depends(get_current_user)):
    rows = (
        db.query(db_models.AIPrediction, db_models.ChatSession, db_models.User)
        .join(db_models.ChatSession, db_models.AIPrediction.session_id == db_models.ChatSession.id)
        .join(db_models.User, db_models.ChatSession.user_id == db_models.User.id)
        .all()
    )

    buffer = io.StringIO()
    writer = csv.writer(buffer)
    writer.writerow([
        "participant_code", "session_uuid", "started_at", "completed_at",
        "depression_score", "depression_risk", "anxiety_score", "anxiety_risk",
        "stress_score", "stress_risk", "overall_wellness_score", "confidence_score",
        "ml_predicted_risk",
    ])
    for prediction, session, user in rows:
        writer.writerow([
            user.participant_code, session.session_uuid, session.started_at,
            session.completed_at, prediction.depression_score, prediction.depression_risk_level,
            prediction.anxiety_score, prediction.anxiety_risk_level,
            prediction.stress_score, prediction.stress_risk_level,
            prediction.overall_wellness_score, prediction.confidence_score,
            prediction.ml_predicted_risk,
        ])

    buffer.seek(0)
    return StreamingResponse(
        buffer, media_type="text/csv",
        headers={"Content-Disposition": "attachment; filename=mindscreen_export_anonymized.csv"},
    )
