from __future__ import annotations

from django.utils import timezone

from market.models import SellerProfile
from market.services.access import resolve_company_for_user

from contract.services.dashboard_reports import build_dashboard_reports
from contract.services.dashboard_widgets import (
    RANGE_OPTIONS,
    build_dashboard_filters,
    build_dashboard_meta,
    build_dashboard_quick_actions,
    resolve_dashboard_profile,
)


DEFAULT_RANGE_DAYS = 90
ALLOWED_RANGE_DAYS = {value for value, _label in RANGE_OPTIONS}
PROFILE_LABELS = {
    "admin": "Admin / Superuser",
    "field_officer": "Field Officer",
    "farmer": "Farmer",
    "seller": "Seller / Business",
    "company": "Company / Factory",
    "operations": "Operations",
}


def _parse_range_days(raw_value) -> int:
    try:
        value = int(raw_value)
    except (TypeError, ValueError):
        return DEFAULT_RANGE_DAYS
    if value in ALLOWED_RANGE_DAYS:
        return value
    return DEFAULT_RANGE_DAYS


def build_dashboard_context(request) -> dict:
    user = request.user
    selected_range = _parse_range_days(request.GET.get("range"))
    generated_at = timezone.now()
    if timezone.is_aware(generated_at):
        generated_at = timezone.localtime(generated_at)
    seller_profile = (
        SellerProfile.objects.select_related("reviewed_by")
        .filter(user=user)
        .first()
    )
    company_profile = resolve_company_for_user(user)
    profile = resolve_dashboard_profile(user, seller_profile, company_profile)
    dashboard_meta = build_dashboard_meta(user, profile)
    dashboard_reports = build_dashboard_reports(
        user,
        profile,
        days=selected_range,
        seller_profile=seller_profile,
        company_profile=company_profile,
    )

    sections = dashboard_reports.get("sections", [])
    charts = [
        chart
        for section in sections
        for chart in section.get("charts", [])
    ]

    context = {
        "dashboard_profile": profile,
        "dashboard_profile_label": PROFILE_LABELS.get(profile, "Operations"),
        "dashboard_meta": dashboard_meta,
        "dashboard_selected_range": selected_range,
        "dashboard_filters": build_dashboard_filters(request, selected_range),
        "dashboard_quick_actions": build_dashboard_quick_actions(user, profile, seller_profile, company_profile),
        "dashboard_kpis": dashboard_reports.get("kpis", []),
        "dashboard_alerts": dashboard_reports.get("alerts", []),
        "dashboard_summary_cards": dashboard_reports.get("summary_cards", []),
        "dashboard_sections": sections,
        "dashboard_activity": dashboard_reports.get("activity", []),
        "dashboard_chart_count": len(charts),
        "dashboard_generated_at": generated_at,
        "dashboard_sections_open_by_default": 2,
    }

    return context
