import asyncio
import json
import time
from datetime import datetime

import httpx

ENDPOINTS = [
    {
        "name": "Landing Page",
        "url": "https://dinhsonconstruction.com/",
        "expected_status": 200,
    },
    {
        "name": "API Health Liveness",
        "url": "https://dinhsonconstruction.com/health",
        "expected_status": 200,
    },
    {
        "name": "API Health Alias",
        "url": "https://dinhsonconstruction.com/api/health",
        "expected_status": 200,
    },
    {
        "name": "API System Readiness",
        "url": "https://dinhsonconstruction.com/health/readiness",
        "expected_status": 200,
    },
    {
        "name": "OpenAPI Documentation",
        "url": "https://dinhsonconstruction.com/docs",
        "expected_status": 200,
    },
    {
        "name": "Authentication Page",
        "url": "https://dinhsonconstruction.com/login",
        "expected_status": 200,
    },
    {
        "name": "Executive Master Dashboard",
        "url": "https://dinhsonconstruction.com/dashboard",
        "expected_status": 200,
    },
    {
        "name": "Projects & WBS Management",
        "url": "https://dinhsonconstruction.com/dashboard/projects",
        "expected_status": 200,
    },
    {
        "name": "GDT E-Invoices Ledger",
        "url": "https://dinhsonconstruction.com/dashboard/invoices",
        "expected_status": 200,
    },
    {
        "name": "HRM & Fleet Machines",
        "url": "https://dinhsonconstruction.com/dashboard/employees",
        "expected_status": 200,
    },
    {
        "name": "QA/QC Readiness Dossier",
        "url": "https://dinhsonconstruction.com/dashboard/readiness",
        "expected_status": 200,
    },
    {
        "name": "Construction Documents Vault",
        "url": "https://dinhsonconstruction.com/dashboard/documents",
        "expected_status": 200,
    },
    {
        "name": "RBAC User Control",
        "url": "https://dinhsonconstruction.com/dashboard/users",
        "expected_status": 200,
    },
    {
        "name": "Partners & Supply Chain Hub",
        "url": "https://dinhsonconstruction.com/dashboard/partners",
        "expected_status": 200,
    },
    {
        "name": "Financial War Room",
        "url": "https://dinhsonconstruction.com/dashboard/war-room",
        "expected_status": 200,
    },
    {
        "name": "DeepSeek DHS Agentic Hub",
        "url": "https://dinhsonconstruction.com/dashboard/agent-models",
        "expected_status": 200,
    },
    {
        "name": "Site Diary Mobile PWA",
        "url": "https://dinhsonconstruction.com/dashboard/site-diary-mobile",
        "expected_status": 200,
    },
    {
        "name": "AI Drawing Takeoff Hub",
        "url": "https://dinhsonconstruction.com/dashboard/drawing-takeoff",
        "expected_status": 200,
    },
    {
        "name": "Unified Enterprise CSS",
        "url": "https://dinhsonconstruction.com/static/css/erp_enterprise.css",
        "expected_status": 200,
    },
    {
        "name": "Navigation Dock JS",
        "url": "https://dinhsonconstruction.com/static/js/erp_mobile_dock.js",
        "expected_status": 200,
    },
    {
        "name": "ERP Subdomain Alias",
        "url": "https://erp.dinhsonconstruction.com/",
        "expected_status": 200,
    },
    {
        "name": "Protected Company State API (Unauth)",
        "url": "https://dinhsonconstruction.com/v1/company/operational-state",
        "expected_status": 401,
    },
    {
        "name": "Protected Invoices List API (Unauth)",
        "url": "https://dinhsonconstruction.com/v1/erp/invoices/list",
        "expected_status": 401,
    },
    {
        "name": "Protected Projects List API (Unauth)",
        "url": "https://dinhsonconstruction.com/v1/projects",
        "expected_status": 401,
    },
]


async def run_audit():
    results = []
    print(
        f"[{datetime.now().isoformat()}] Bat dau quet kiem tra dinhsonconstruction.com..."
    )

    async with httpx.AsyncClient(timeout=10.0, follow_redirects=True) as client:
        for ep in ENDPOINTS:
            t0 = time.perf_counter()
            try:
                resp = await client.get(ep["url"])
                duration_ms = round((time.perf_counter() - t0) * 1000, 1)
                cf_ray = resp.headers.get("cf-ray", "N/A")
                content_type = resp.headers.get("content-type", "N/A")
                content_len = len(resp.content)
                status_match = resp.status_code == ep["expected_status"]

                res_obj = {
                    "name": ep["name"],
                    "url": ep["url"],
                    "status_code": resp.status_code,
                    "expected_status": ep["expected_status"],
                    "status_match": status_match,
                    "duration_ms": duration_ms,
                    "content_length": content_len,
                    "content_type": content_type,
                    "cf_ray": cf_ray,
                    "passed": status_match,
                }
                results.append(res_obj)
                print(
                    f" -> [{resp.status_code}] {ep['name']} ({duration_ms} ms) - CF-RAY: {cf_ray}"
                )
            except Exception as e:
                duration_ms = round((time.perf_counter() - t0) * 1000, 1)
                res_obj = {
                    "name": ep["name"],
                    "url": ep["url"],
                    "status_code": "ERROR",
                    "expected_status": ep["expected_status"],
                    "status_match": False,
                    "duration_ms": duration_ms,
                    "content_length": 0,
                    "content_type": "N/A",
                    "cf_ray": "N/A",
                    "error": str(e),
                    "passed": False,
                }
                results.append(res_obj)
                print(f" -> [FAIL] {ep['name']}: {e}")

    with open("docs/audits/latest_scan_results.json", "w", encoding="utf-8") as f:
        json.dump(results, f, ensure_ascii=False, indent=2)

    print("Quet hoan tat. Du lieu da luu vao docs/audits/latest_scan_results.json")
    return results


if __name__ == "__main__":
    asyncio.run(run_audit())
