from __future__ import annotations

from pathlib import Path
from typing import Any, Final

from fastapi import Request


DASHBOARD_PATH: Final[str] = "/dashboard"
RIPS_OPERATIVO_PATH: Final[str] = "/rips/operativo"
CASES_PATH: Final[str] = "/casos"
EPICRISIS_PATH: Final[str] = "/epicrisis"

_SIDEBAR_EXCLUDED_PATHS = frozenset({DASHBOARD_PATH, RIPS_OPERATIVO_PATH})
_BASE_DIR = Path(__file__).resolve().parents[2]
_CASE_UPLOAD_ASSET_PATHS = (
    _BASE_DIR / "static/js/case-upload-dialog.js",
    _BASE_DIR / "static/css/styles/organisms/_case-upload-dialog.css",
    _BASE_DIR / "web/includes/case_upload_dialog.html",
)


def _case_upload_asset_version() -> str:
    latest_mtime = 0
    for asset_path in _CASE_UPLOAD_ASSET_PATHS:
        try:
            latest_mtime = max(latest_mtime, int(asset_path.stat().st_mtime))
        except OSError:
            continue
    return str(latest_mtime or 1)


def _user_role(user: Any) -> str:
    return str(getattr(user, "role", "") or "").strip().lower()


def _base_navigation_items() -> list[dict[str, Any]]:
    return [
        {
            "id": "home",
            "label": "Inicio",
            "href": DASHBOARD_PATH,
            "icon": "home",
            "active_paths": [DASHBOARD_PATH],
            "section": "primary",
        },
        {
            "id": "upload",
            "label": "Nuevo cargue",
            "href": "#app-shell-new-upload",
            "dashboard_href": "#dashboard-quick-upload",
            "icon": "file-upload",
            "active_paths": [],
            "action": "open-upload",
            "upload_mode": "story",
            "section": "primary",
            "featured": True,
        },
        {
            "id": "cases",
            "label": "Casos",
            "href": CASES_PATH,
            "icon": "folders",
            "active_paths": [CASES_PATH, EPICRISIS_PATH, f"{EPICRISIS_PATH}/", "/paciente/epicrisis"],
            "section": "primary",
        },
        {
            "id": "batches",
            "label": "Carga masiva",
            "href": "/subir_lote",
            "icon": "stack-2",
            "active_paths": ["/subir_lote"],
            "section": "primary",
        },
        {
            "id": "soat",
            "label": "SOAT",
            "href": "/soat_agent",
            "icon": "shield",
            "active_paths": ["/soat_agent"],
            "section": "tools",
        },
        {
            "id": "soat-chat",
            "label": "Chat SOAT",
            "href": "/soat_chat",
            "icon": "messages",
            "active_paths": ["/soat_chat"],
            "section": "tools",
        },
        {
            "id": "rips",
            "label": "RIPS",
            "href": RIPS_OPERATIVO_PATH,
            "icon": "table-column",
            "active_paths": [RIPS_OPERATIVO_PATH],
            "section": "tools",
        },
        {
            "id": "profile",
            "label": "Perfil",
            "href": "/perfil",
            "icon": "user-check",
            "active_paths": ["/perfil"],
            "section": "account",
        },
    ]


def _admin_navigation_item() -> dict[str, Any]:
    return {
        "id": "admin",
        "label": "Panel admin",
        "href": "/panel-admin",
        "icon": "settings-check",
        "active_paths": ["/panel-admin", "/admin/"],
        "section": "account",
    }


def _is_active_path(path: str, active_paths: list[str]) -> bool:
    normalized_path = str(path or "").strip() or "/"
    for candidate in active_paths:
        if candidate.endswith("/") and normalized_path.startswith(candidate):
            return True
        if normalized_path == candidate:
            return True
    return False


def build_dashboard_navigation(user: Any) -> list[dict[str, Any]]:
    items = [dict(item) for item in _base_navigation_items()]
    if _user_role(user) == "admin":
        items.append(_admin_navigation_item())
    return items


def should_render_app_sidebar(request: Request) -> bool:
    return request.url.path not in _SIDEBAR_EXCLUDED_PATHS


def build_shell_context(*, request: Request, user: Any) -> dict[str, Any]:
    nav_items = build_dashboard_navigation(user)
    current_path = request.url.path
    resolved_items = [
        {
            **item,
            "is_active": _is_active_path(current_path, item.get("active_paths") or []),
        }
        for item in nav_items
    ]
    section_meta = [
        {"id": "primary", "label": "Operación"},
        {"id": "tools", "label": "Herramientas"},
        {"id": "account", "label": "Cuenta"},
    ]
    return {
        "shell_sidebar_enabled": should_render_app_sidebar(request),
        "case_upload_asset_version": _case_upload_asset_version(),
        "shell_sidebar_nav": resolved_items,
        "shell_sidebar_sections": [
            {
                **section,
                "nav_items": [item for item in resolved_items if item.get("section") == section["id"]],
            }
            for section in section_meta
            if any(item.get("section") == section["id"] for item in resolved_items)
        ],
    }
