from __future__ import annotations

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

from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.core.responses import api_success
from app.models.user import User
from app.schemas.user import UserProfile
from app.services.entitlement_service import EntitlementService, entitlement_dict
from app.services.growth_profile_service import GrowthProfileService, growth_profile_dict
from app.services.periodic_report_service import PeriodicReportService, periodic_report_dict
from app.services.topic_session_service import TopicSessionService

router = APIRouter()


@router.get("/profile")
def profile(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> dict:
    data = UserProfile.model_validate(current_user).model_dump(mode="json")
    view = EntitlementService.active_entitlement(
        db,
        current_user,
        monthly_topic_used=TopicSessionService.monthly_used_count(db, current_user.id),
    )
    data["entitlement"] = entitlement_dict(view)
    return api_success(data)


@router.get("/growth-profile")
def growth_profile(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> dict:
    profile = GrowthProfileService.get_growth_profile(db, current_user.id)
    summaries = GrowthProfileService.recent_topic_summaries(db, current_user.id, limit=10)
    return api_success(
        {
            "profile": growth_profile_dict(profile),
            "recentSummaries": [
                {
                    "id": item.id,
                    "topicSessionId": item.topic_session_id,
                    "schemaVersion": item.schema_version,
                    "summary": item.summary,
                    "currentFocus": item.main_events,
                    "nextObservation": item.next_observation,
                    "status": item.status,
                    "errorMessage": item.error_message,
                    "attemptCount": item.attempt_count,
                    "maxAttempts": item.max_attempts,
                    "nextRunAt": item.next_run_at,
                    "lastStartedAt": item.last_started_at,
                    "finishedAt": item.finished_at,
                    "generatedAt": item.generated_at,
                }
                for item in summaries
            ],
        }
    )


@router.get("/periodic-report/list")
def periodic_reports(
    limit: int = 20,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> dict:
    reports = PeriodicReportService.list_user_reports(
        db,
        user_id=current_user.id,
        limit=max(1, min(limit, 50)),
        statuses=("success",),
    )
    return api_success([periodic_report_dict(item) for item in reports])
