from __future__ import annotations

from datetime import datetime
from pathlib import Path
from typing import Callable

from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse, Response

from .admin_db_status import fetch_db_status_snapshot, fetch_db_table_preview


def register_system_routes(
    app: FastAPI,
    *,
    upload_dir: Path,
    legacy_dir: Path,
    incoming_files_dir: Path,
    incoming_served_dir: Path,
    db_status_served_dir: Path,
    business_ledger_index_path: Path,
    get_member_count: Callable[[], int],
    get_conn,
    build_business_ledger_default_response: Callable[[object], Response],
    build_ledger_index_response: Callable[[Path], FileResponse],
) -> None:
    @app.get("/api/health")
    def health() -> dict[str, object]:
        checks = {
            "upload_dir": upload_dir.exists(),
        }

        try:
            member_count = get_member_count()
            checks["database"] = True
        except Exception:
            member_count = None
            checks["database"] = False

        status = "ok" if all(checks.values()) else "degraded"
        return {
            "status": status,
            "checks": checks,
            "member_count": member_count,
            "timestamp": datetime.utcnow().isoformat() + "Z",
        }

    @app.get("/api/admin/db-status")
    def admin_db_status() -> dict[str, object]:
        return fetch_db_status_snapshot()

    @app.get("/api/admin/db-status/table")
    def admin_db_status_table(schema: str, table: str, limit: int = 50) -> dict[str, object]:
        return fetch_db_table_preview(schema, table, limit)

    @app.get("/admin/db-status")
    def admin_db_status_view() -> FileResponse:
        target = db_status_served_dir / "index.html"
        if not target.exists():
            raise HTTPException(status_code=404, detail="DB status dashboard file not found.")
        response = FileResponse(target)
        response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
        response.headers["Pragma"] = "no-cache"
        return response

    @app.get("/api/integration/business-ledger-default")
    def integration_business_ledger_default() -> Response:
        with get_conn() as conn:
            with conn.cursor() as cur:
                return build_business_ledger_default_response(cur)

    @app.get("/api/integration/mh-workbook")
    def integration_mh_workbook() -> FileResponse:
        target = incoming_files_dir / "MH.xlsx"
        if not target.exists():
            raise HTTPException(status_code=404, detail="MH workbook not found.")
        return FileResponse(
            target,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            filename="MH.xlsx",
        )

    @app.get("/legacy/organization")
    def legacy_organization() -> FileResponse:
        target = legacy_dir / "DashBoard-organization.html"
        if not target.exists():
            raise HTTPException(status_code=404, detail="Legacy dashboard file not found.")
        return FileResponse(target)

    @app.get("/legacy/organization-backup")
    def legacy_organization_backup() -> FileResponse:
        target = legacy_dir / "DashBoard-organization-backup.html"
        if not target.exists():
            raise HTTPException(status_code=404, detail="Legacy dashboard backup not found.")
        return FileResponse(target)

    @app.get("/integrations/payment")
    def integration_payment() -> FileResponse:
        target = incoming_served_dir / "payment.html"
        if not target.exists():
            raise HTTPException(status_code=404, detail="Payment integration file not found.")
        return FileResponse(target)

    @app.get("/integrations/ledger")
    def integration_ledger() -> FileResponse:
        return build_ledger_index_response(business_ledger_index_path)

    @app.get("/integrations/mh")
    def integration_mh() -> FileResponse:
        target = incoming_served_dir / "mh.html"
        if not target.exists():
            raise HTTPException(status_code=404, detail="MH integration file not found.")
        return FileResponse(target)

    @app.get("/uploads/{filename}")
    def get_upload(filename: str) -> FileResponse:
        target = upload_dir / filename
        if not target.exists():
            raise HTTPException(status_code=404, detail="Upload not found.")
        return FileResponse(target)
