"""Health and static asset routes for DSCons."""

from __future__ import annotations

from pathlib import Path

from fastapi import APIRouter, Request, Response
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse

from app.models.schemas import HealthResponse
from app.modules.projects.application.project_management_service import ProjectManagementService

router = APIRouter()
STATIC_DIR = Path(__file__).resolve().parents[3] / "static"


def _read_static_page(filename: str) -> HTMLResponse:
    """Read one static HTML page from the shared static directory with zero-cache headers."""
    content = (STATIC_DIR / filename).read_text(encoding="utf-8")
    return HTMLResponse(
        content=content,
        headers={
            "Cache-Control": "no-cache, no-store, must-revalidate, max-age=0",
            "Pragma": "no-cache",
            "Expires": "0",
        },
    )


@router.get("/health", response_model=HealthResponse, include_in_schema=False)
@router.get("/api/health", response_model=HealthResponse, include_in_schema=False)
@router.get("/api/v1/health", response_model=HealthResponse)
def health_check() -> HealthResponse:
    """Simple liveness check endpoint."""
    return HealthResponse()


@router.get("/favicon.ico", include_in_schema=False)
@router.get("/favicon.svg", include_in_schema=False)
def favicon_route() -> FileResponse:
    """Serve company favicon with zero-cache headers."""
    fav_path = STATIC_DIR / "favicon.svg"
    return FileResponse(
        str(fav_path),
        media_type="image/svg+xml",
        headers={
            "Cache-Control": "no-cache, no-store, must-revalidate, max-age=0",
            "Pragma": "no-cache",
            "Expires": "0",
        },
    )


@router.get("/health/readiness")
def readiness_check() -> JSONResponse:
    """Return dependency readiness for PostgreSQL and static assets."""
    static_files = {
        "index": (STATIC_DIR / "index.html").exists(),
        "login": (STATIC_DIR / "login.html").exists(),
        "landing": (STATIC_DIR / "landing.html").exists(),
        "readiness_dashboard": (STATIC_DIR / "readiness_dashboard.html").exists(),
        "employee_logs_dashboard": (
            STATIC_DIR / "employee_logs_dashboard.html"
        ).exists(),
        "equipment_dashboard": (STATIC_DIR / "equipment_dashboard.html").exists(),
        "project_management_dashboard": (
            STATIC_DIR / "project_management_dashboard.html"
        ).exists(),
        "documents_dashboard": (STATIC_DIR / "documents_dashboard.html").exists(),
        "agent_management_dashboard": (
            STATIC_DIR / "agent_management_dashboard.html"
        ).exists(),
    }

    from app.core.postgres.base_pkg.base_client import BasePostgresClient

    db_client = BasePostgresClient()
    postgres_enabled = db_client.is_enabled()
    postgres_ready = False
    postgres_error: str | None = None

    if postgres_enabled:
        try:
            postgres_ready = db_client.ping()
        except Exception as exc:
            postgres_error = str(exc)

    checks = {
        "application": {"ready": True},
        "postgres": {
            "enabled": postgres_enabled,
            "ready": postgres_ready if postgres_enabled else False,
            "error": postgres_error,
        },
        "static_assets": {
            "ready": all(static_files.values()),
            "files": static_files,
        },
    }
    overall_ready = (
        checks["application"]["ready"]
        and checks["static_assets"]["ready"]
        and (postgres_ready if postgres_enabled else True)
    )

    status_code = 200 if overall_ready else 503
    return JSONResponse(
        status_code=status_code,
        content={
            "status": "ready" if overall_ready else "degraded",
            "checks": checks,
        },
    )


@router.get("/", response_class=HTMLResponse)
def homepage(request: Request) -> Response:
    """Serve the public corporate landing page at the root domain or redirect ERP."""
    host = request.headers.get("host", "").lower()
    if host.startswith("erp."):
        return RedirectResponse(url="/v1/erp/dashboard", status_code=302)
    return _read_static_page("landing.html")


@router.get("/landing", response_class=HTMLResponse)
def landing_page() -> HTMLResponse:
    """Serve the company corporate landing page."""
    return _read_static_page("landing.html")


@router.get("/v1/erp/dashboard", response_class=HTMLResponse)
@router.get("/v1/erp/erp", response_class=HTMLResponse, include_in_schema=False)
def erp_dashboard() -> HTMLResponse:
    """Serve the main enterprise ERP Command Center dashboard."""
    return _read_static_page("index.html")


@router.get("/v1/erp/login", response_class=HTMLResponse)
def login_page() -> HTMLResponse:
    """Serve the Google Auth and enterprise login page."""
    return _read_static_page("login.html")


@router.get("/v1/erp/dashboard/readiness", response_class=HTMLResponse)
@router.get("/v1/erp/readiness", response_class=HTMLResponse)
def readiness_dashboard() -> HTMLResponse:
    """Serve the dossier readiness dashboard."""
    return _read_static_page("readiness_dashboard.html")


@router.get("/v1/erp/dashboard/employees", response_class=HTMLResponse)
@router.get("/v1/erp/dashboard/site-diary", response_class=HTMLResponse)
def employee_logs_dashboard() -> HTMLResponse:
    """Serve the enterprise HRM and site operations dashboard."""
    return _read_static_page("employee_logs_dashboard.html")


@router.get("/v1/erp/dashboard/equipment", response_class=HTMLResponse)
def equipment_dashboard() -> HTMLResponse:
    """Serve the enterprise machinery, vehicles and fleet management dashboard."""
    return _read_static_page("equipment_dashboard.html")


@router.get("/v1/erp/dashboard/projects", response_class=HTMLResponse)
@router.get("/v1/erp/dashboard/wbs", response_class=HTMLResponse)
def project_management_dashboard() -> HTMLResponse:
    """Serve the project management dashboard."""
    return _read_static_page("project_management_dashboard.html")


@router.get("/v1/erp/dashboard/documents", response_class=HTMLResponse)
@router.get("/v1/erp/documents-dashboard", response_class=HTMLResponse)
def documents_dashboard() -> HTMLResponse:
    """Serve the enterprise document management dashboard."""
    return _read_static_page("documents_dashboard.html")


@router.get("/v1/erp/dashboard/users", response_class=HTMLResponse)
def users_dashboard() -> HTMLResponse:
    """Serve the user management and role assignment dashboard."""
    return _read_static_page("users_dashboard.html")


@router.get("/v1/erp/dashboard/settings", response_class=HTMLResponse)
def settings_dashboard() -> HTMLResponse:
    """Serve the enterprise global configuration dashboard."""
    return _read_static_page("settings_dashboard.html")

import httpx

@router.get("/v1/erp/settings/lmstudio-models")
async def get_lmstudio_models():
    """Proxy endpoint to fetch available models from local LMStudio."""
    try:
        async with httpx.AsyncClient() as client:
            resp = await client.get("http://127.0.0.1:1234/v1/models", timeout=2.0)
            if resp.status_code == 200:
                data = resp.json()
                models = []
                for model in data.get("data", []):
                    # Usually id is the model name in LMStudio
                    models.append({"value": model["id"], "label": model["id"]})
                return {"success": True, "models": models}
            return {"success": False, "models": []}
    except Exception as e:
        import logging
        logging.getLogger("dscons.app").error(f"Failed to fetch LMStudio models: {e}")
        return {"success": False, "models": []}


@router.get("/v1/erp/dashboard/invoices", response_class=HTMLResponse)
def invoices_dashboard() -> HTMLResponse:
    """Serve the enterprise e-invoice and tax management dashboard."""
    return _read_static_page("invoices_dashboard.html")


@router.get("/v1/erp/dashboard/banking", response_class=HTMLResponse)
def banking_reconciliation_dashboard() -> HTMLResponse:
    """Serve the enterprise bank statement parsing and reconciliation dashboard."""
    return _read_static_page("banking_reconciliation_dashboard.html")


@router.get("/v1/erp/dashboard/customers", response_class=HTMLResponse)
@router.get("/v1/erp/dashboard/partners", response_class=HTMLResponse)
@router.get("/v1/erp/dashboard/vendors", response_class=HTMLResponse)
def partners_dashboard() -> HTMLResponse:
    """Serve the enterprise customers, partners and vendor management dashboard."""
    return _read_static_page("partners_dashboard.html")


@router.get("/v1/erp/dashboard/zalo_crm", response_class=HTMLResponse)
def zalo_crm_dashboard() -> HTMLResponse:
    """Serve the Zalo CRM module dashboard."""
    return _read_static_page("zalo_crm_dashboard.html")


@router.get("/v1/erp/dashboard/war-room", response_class=HTMLResponse)
@router.get("/v1/erp/dashboard/finance", response_class=HTMLResponse)
def financial_war_room_dashboard() -> HTMLResponse:
    """Serve the executive financial war room and cashflow runway dashboard."""
    return _read_static_page("financial_war_room_dashboard.html")


@router.get("/v1/erp/dashboard/site-diary-mobile", response_class=HTMLResponse)
def site_diary_mobile_page() -> HTMLResponse:
    """Serve the mobile site diary and material requisition PWA."""
    return _read_static_page("site_diary_mobile.html")


@router.get("/v1/erp/dashboard/agent-models", response_class=HTMLResponse)
@router.get("/v1/erp/dashboard/agents", response_class=HTMLResponse)
@router.get("/v1/erp/dashboard/dhs", response_class=HTMLResponse)
def agent_models_dashboard() -> HTMLResponse:
    """Serve the enterprise AI Agent Management, DeepSeek Harness (DHS) & Model Benchmark dashboard."""
    return _read_static_page("agent_management_dashboard.html")


@router.get("/v1/erp/dashboard/material-prices", response_class=HTMLResponse)
@router.get("/v1/erp/dashboard/material-price-comparison", response_class=HTMLResponse)
def material_price_comparison_page() -> HTMLResponse:
    """Serve the State vs Market Material Price Comparison and Bidding Profit/Loss Benchmark dashboard."""
    return _read_static_page("material_price_comparison.html")


@router.get("/v1/erp/dashboard/drawing-takeoff", response_class=HTMLResponse)
@router.get("/v1/erp/dashboard/takeoff", response_class=HTMLResponse)
def drawing_takeoff_page() -> HTMLResponse:
    """Serve the AI Drawing Takeoff & Automated BoQ Extraction Hub."""
    return _read_static_page("drawing_takeoff_dashboard.html")
