"""Comprehensive System Health Audit and Self-Healing Diagnostics Suite for DSCons.

Scans all system services, database connectivity, AI engine, Cloudflare Tunnel,
mesh network (Tailscale), and verifies public website dinhsonconstruction.com and erp.dinhsonconstruction.com.
Saves persistent audit logs with full timestamps and execution traces.
"""

from __future__ import annotations

import asyncio
import datetime
import json
import logging
import socket
import subprocess
import sys
from pathlib import Path

# Add project root to sys.path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

import time
from concurrent.futures import ThreadPoolExecutor
from typing import Any

import httpx

# Configure logging
LOG_DIR = Path("C:/Projects/DSCons/logs/health_checks")
STORAGE_LOG_DIR = Path("C:/Projects/DSCons/storage/logs")
DOCS_AUDIT_DIR = Path("C:/Projects/DSCons/docs/audits")

LOG_DIR.mkdir(parents=True, exist_ok=True)
STORAGE_LOG_DIR.mkdir(parents=True, exist_ok=True)
DOCS_AUDIT_DIR.mkdir(parents=True, exist_ok=True)

audit_log_file = LOG_DIR / "system_health.log"
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s - %(message)s",
    handlers=[
        logging.FileHandler(audit_log_file, encoding="utf-8"),
        logging.StreamHandler(sys.stdout),
    ],
)
logger = logging.getLogger("dscons.health_audit")


class SystemHealthAuditor:
    """Performs full system diagnostics, auto-remediation, and audit logging."""

    def __init__(self) -> None:
        self.timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat()
        self.report: dict[str, Any] = {
            "timestamp_utc": self.timestamp,
            "overall_status": "UNKNOWN",
            "system_services": {},
            "ports": {},
            "database": {},
            "ai_engines": {},
            "network_mesh": {},
            "public_domains": {},
            "remediation_actions": [],
        }

    def check_tcp_port(self, host: str, port: int, timeout: float = 1.5) -> bool:
        """Checks if a TCP port is open and accepting connections."""
        try:
            with socket.create_connection((host, port), timeout=timeout):
                return True
        except (TimeoutError, ConnectionRefusedError, OSError):
            return False

    def scan_windows_services(self) -> dict[str, Any]:
        """Scans Windows Services state via PowerShell."""
        logger.info("Scanning Windows Services...")
        services_to_check = [
            "postgresql-x64-16",
            "Cloudflared",
            "sshd",
            "com.docker.service",
        ]
        status: dict[str, Any] = {}
        try:
            cmd = subprocess.run(
                [
                    "powershell",
                    "-NoProfile",
                    "-Command",
                    "Get-Service -Name postgresql-x64-16, Cloudflared, sshd, com.docker.service -ErrorAction SilentlyContinue | Select-Object Name, Status, StartType | ConvertTo-Json",
                ],
                capture_output=True,
                text=True,
                timeout=10,
            )
            if cmd.returncode == 0 and cmd.stdout.strip():
                try:
                    parsed = json.loads(cmd.stdout)
                    if isinstance(parsed, dict):
                        parsed = [parsed]
                    for s in parsed:
                        name = s.get("Name", "")
                        st = s.get("Status", 0)
                        # In PS, Status: 4 is Running, 1 is Stopped
                        status_str = (
                            "Running"
                            if st == 4 or str(st).lower() == "running"
                            else "Stopped"
                        )
                        status[name] = {
                            "status": status_str,
                            "start_type": s.get("StartType", "Unknown"),
                            "healthy": status_str == "Running",
                        }
                except Exception as e:
                    logger.warning("Could not parse Get-Service JSON: %s", e)
        except Exception as e:
            logger.warning("Windows service scan failed: %s", e)

        for s in services_to_check:
            if s not in status:
                status[s] = {"status": "Not Installed / Unknown", "healthy": False}
        return status

    def scan_ports(self) -> dict[str, Any]:
        """Scans vital local ports."""
        logger.info("Scanning vital local ports...")
        port_map = {
            22: "OpenSSH Server",
            1234: "LM Studio Local LLM API",
            3389: "Windows Remote Desktop (RDP)",
            5432: "PostgreSQL Database Engine",
            8000: "FastAPI DSCons ERP Backend",
            11434: "Ollama Local AI API",
        }
        results = {}
        for port, desc in port_map.items():
            is_open = self.check_tcp_port("127.0.0.1", port)
            results[str(port)] = {
                "description": desc,
                "open": is_open,
                "status": "OPEN" if is_open else "CLOSED",
            }
        return results

    def inspect_database(self) -> dict[str, Any]:
        """Inspects local PostgreSQL database connectivity and table stats."""
        logger.info("Inspecting PostgreSQL database health...")
        res: dict[str, Any] = {"connected": False, "table_count": 0, "error": None}
        try:
            from app.modules.projects.application.project_management_service import ProjectManagementService

            pg = ProjectManagementService()._postgres_client
            if pg.is_enabled():
                with pg.get_connection() as conn:
                    with conn.cursor() as cur:
                        cur.execute(
                            "SELECT count(*) AS total FROM information_schema.tables WHERE table_schema='public';"
                        )
                        row_count = cur.fetchone()
                        count = (
                            row_count["total"]
                            if isinstance(row_count, dict)
                            else row_count[0]
                        )
                        cur.execute("SELECT version() AS ver;")
                        row_ver = cur.fetchone()
                        version = (
                            row_ver["ver"] if isinstance(row_ver, dict) else row_ver[0]
                        )
                        res["connected"] = True
                        res["table_count"] = count
                        res["version"] = version
                        res["status"] = "HEALTHY"

            else:
                res["status"] = "DISABLED_IN_CONFIG"
        except Exception as e:
            logger.warning("PostgreSQL inspection error: %s", e)
            res["error"] = str(e)
            res["status"] = "ERROR"
        return res

    async def inspect_ai_engines(self) -> dict[str, Any]:
        """Inspects local AI providers (LM Studio, Ollama)."""
        logger.info("Inspecting local AI providers...")
        ai_status: dict[str, Any] = {}

        # 1. LM Studio (Port 1234)
        lm_running = False
        lm_models = []
        try:
            async with httpx.AsyncClient(timeout=2.0) as client:
                resp = await client.get("http://127.0.0.1:1234/v1/models")
                if resp.status_code == 200:
                    lm_running = True
                    data = resp.json()
                    lm_models = [m.get("id") for m in data.get("data", [])]
        except Exception:
            pass
        ai_status["lm_studio"] = {
            "endpoint": "http://127.0.0.1:1234",
            "available": lm_running,
            "models": lm_models,
            "status": "ONLINE" if lm_running else "OFFLINE",
        }

        # 2. Ollama (Port 11434)
        ollama_running = False
        ollama_models = []
        try:
            async with httpx.AsyncClient(timeout=2.0) as client:
                resp = await client.get("http://127.0.0.1:11434/api/tags")
                if resp.status_code == 200:
                    ollama_running = True
                    data = resp.json()
                    ollama_models = [m.get("name") for m in data.get("models", [])]
        except Exception:
            pass
        ai_status["ollama"] = {
            "endpoint": "http://127.0.0.1:11434",
            "available": ollama_running,
            "models": ollama_models,
            "status": "ONLINE" if ollama_running else "OFFLINE",
        }

        return ai_status

    def scan_tailscale(self) -> dict[str, Any]:
        """Scans Tailscale mesh network and remote development peers."""
        logger.info("Scanning Tailscale mesh network and remote hosts...")
        result: dict[str, Any] = {
            "installed": False,
            "running": False,
            "self": {},
            "peers": [],
        }
        try:
            cmd = subprocess.run(
                ["tailscale", "status", "--json"],
                capture_output=True,
                text=True,
                timeout=5,
            )
            if cmd.returncode == 0:
                result["installed"] = True
                result["running"] = True
                data = json.loads(cmd.stdout)
                self_node = data.get("Self", {})
                result["self"] = {
                    "hostname": self_node.get("HostName"),
                    "ip": self_node.get("TailscaleIPs", [""])[0],
                    "os": self_node.get("OS"),
                    "online": self_node.get("Online", True),
                }

                # Check peers and their diagnostic ports
                with ThreadPoolExecutor(max_workers=5) as executor:
                    for peer in data.get("Peer", {}).values():
                        p_name = peer.get("HostName", "")
                        p_ip = peer.get("TailscaleIPs", [""])[0]
                        p_os = peer.get("OS", "")
                        p_online = peer.get("Online", False)

                        # Test ports if peer is online
                        port_status = {}
                        if p_online and p_ip:
                            ssh_open = self.check_tcp_port(p_ip, 22, timeout=1.0)
                            ollama_open = self.check_tcp_port(p_ip, 11434, timeout=1.0)
                            rdp_open = self.check_tcp_port(p_ip, 3389, timeout=1.0)
                            port_status = {
                                "ssh_22": ssh_open,
                                "ollama_11434": ollama_open,
                                "rdp_3389": rdp_open,
                            }

                        result["peers"].append(
                            {
                                "hostname": p_name,
                                "ip": p_ip,
                                "os": p_os,
                                "online": p_online,
                                "open_ports": port_status,
                            }
                        )
            else:
                result["installed"] = True
                result["running"] = False
        except Exception as e:
            logger.warning("Tailscale check failed: %s", e)
            result["error"] = str(e)
        return result

    async def verify_public_domains(self) -> dict[str, Any]:
        """Verifies public websites and Cloudflare edge routes."""
        logger.info("Verifying public domains and Cloudflare Edge...")
        urls = [
            ("https://dinhsonconstruction.com/", "Landing Page"),
            ("https://dinhsonconstruction.com/health", "API Health Liveness"),
            (
                "https://dinhsonconstruction.com/health/readiness",
                "API System Readiness",
            ),
            ("https://dinhsonconstruction.com/docs", "Swagger OpenAPI Docs"),
            ("https://dinhsonconstruction.com/dashboard", "ERP Master Dashboard"),
            ("https://dinhsonconstruction.com/login", "Authentication Login"),
            (
                "https://dinhsonconstruction.com/dashboard/readiness",
                "Quality Dossier Readiness",
            ),
            (
                "https://dinhsonconstruction.com/dashboard/employees",
                "HRM & Site Operations",
            ),
            (
                "https://dinhsonconstruction.com/dashboard/equipment",
                "Machinery Fleet Operations",
            ),
            (
                "https://dinhsonconstruction.com/dashboard/projects",
                "Project & WBS Control",
            ),
            (
                "https://dinhsonconstruction.com/dashboard/documents",
                "Document Management",
            ),
            ("https://dinhsonconstruction.com/dashboard/users", "RBAC User Management"),
            (
                "https://dinhsonconstruction.com/dashboard/invoices",
                "E-Invoice & Tax Engine",
            ),
            (
                "https://dinhsonconstruction.com/dashboard/partners",
                "Partners & Vendors Hub",
            ),
            (
                "https://dinhsonconstruction.com/dashboard/war-room",
                "Financial War Room",
            ),
            (
                "https://dinhsonconstruction.com/dashboard/site-diary-mobile",
                "Site Diary Mobile PWA",
            ),
            (
                "https://dinhsonconstruction.com/dashboard/agent-models",
                "AI Agent & DHS Hub",
            ),
            (
                "https://dinhsonconstruction.com/static/css/erp_enterprise.css",
                "Enterprise CSS",
            ),
            (
                "https://dinhsonconstruction.com/static/js/erp_mobile_dock.js",
                "Navigation Dock JS",
            ),
            ("https://erp.dinhsonconstruction.com/", "ERP Subdomain Alias"),
        ]
        results = {}
        async with httpx.AsyncClient(timeout=10.0, follow_redirects=True) as client:
            for url, label in urls:
                try:
                    start_t = time.perf_counter()
                    res = await client.get(url)
                    elapsed_ms = round((time.perf_counter() - start_t) * 1000, 2)
                    cf_ray = res.headers.get("cf-ray", "N/A")
                    server = res.headers.get("server", "N/A")
                    results[url] = {
                        "label": label,
                        "status_code": res.status_code,
                        "response_time_ms": elapsed_ms,
                        "size_bytes": len(res.content),
                        "cf_ray": cf_ray,
                        "server": server,
                        "healthy": res.status_code == 200,
                    }
                except Exception as e:
                    results[url] = {
                        "label": label,
                        "status_code": 0,
                        "error": str(e),
                        "healthy": False,
                    }
        return results

    def auto_remediate(self) -> None:
        """Applies self-healing actions if services or endpoints fail."""
        logger.info("Checking self-healing triggers...")

        # 1. Check PostgreSQL
        if not self.report["ports"].get("5432", {}).get("open"):
            logger.warning(
                "Auto-Remediation: PostgreSQL port 5432 is down. Attempting service start..."
            )
            try:
                subprocess.run(
                    [
                        "powershell",
                        "-NoProfile",
                        "-Command",
                        "Start-Service postgresql-x64-16 -ErrorAction SilentlyContinue",
                    ],
                    capture_output=True,
                    timeout=10,
                )
                self.report["remediation_actions"].append(
                    "Restarted PostgreSQL service (postgresql-x64-16)"
                )
                time.sleep(2)
            except Exception as e:
                logger.error("Failed to start PostgreSQL: %s", e)

        # 2. Check OpenSSH Server
        if not self.report["ports"].get("22", {}).get("open"):
            logger.warning(
                "Auto-Remediation: OpenSSH port 22 is down. Executing OpenSSH self-healing..."
            )
            try:
                cmd_ssh = (
                    "Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0; "
                    "Start-Service sshd; Set-Service -Name sshd -StartupType 'Automatic'; "
                    "New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22"
                )
                subprocess.run(
                    ["powershell", "-NoProfile", "-Command", cmd_ssh],
                    capture_output=True,
                    timeout=15,
                )
                self.report["remediation_actions"].append(
                    "Healed OpenSSH server configuration and started sshd"
                )
            except Exception as e:
                logger.error("Failed to heal OpenSSH: %s", e)

        # 3. Check Local FastAPI Backend
        if not self.report["ports"].get("8000", {}).get("open"):
            logger.warning(
                "Auto-Remediation: FastAPI backend on port 8000 is down. Spawning uvicorn..."
            )
            python_exe = Path("C:/Projects/DSCons/.venv/Scripts/python.exe")
            if python_exe.exists():
                subprocess.Popen(
                    [
                        str(python_exe),
                        "-m",
                        "uvicorn",
                        "app.main:app",
                        "--host",
                        "127.0.0.1",
                        "--port",
                        "8000",
                        "--reload",
                    ],
                    cwd="C:/Projects/DSCons",
                    creationflags=subprocess.CREATE_NEW_PROCESS_GROUP
                    if sys.platform == "win32"
                    else 0,
                )
                self.report["remediation_actions"].append(
                    "Launched FastAPI ERP backend on port 8000"
                )
                # Wait for FastAPI to bind and respond
                for _ in range(25):
                    time.sleep(1)
                    if self.check_tcp_port("127.0.0.1", 8000):
                        logger.info("FastAPI backend successfully bound to port 8000.")
                        break

        # 4. Check Cloudflare Tunnel (only if backend is already up)
        if self.check_tcp_port("127.0.0.1", 8000):
            landing_status = self.report["public_domains"].get(
                "https://dinhsonconstruction.com/", {}
            )
            if not landing_status.get("healthy", False):
                logger.warning(
                    "Auto-Remediation: dinhsonconstruction.com is unresponsive. Checking Cloudflare Tunnel..."
                )
                try:
                    subprocess.run(
                        [
                            "powershell",
                            "-NoProfile",
                            "-Command",
                            "Restart-Service Cloudflared -ErrorAction SilentlyContinue",
                        ],
                        capture_output=True,
                        timeout=10,
                    )
                    self.report["remediation_actions"].append(
                        "Restarted Cloudflared Windows Service"
                    )
                    for _ in range(10):
                        time.sleep(1)
                        if self.check_tcp_port("127.0.0.1", 8000):
                            break
                except Exception as e:
                    logger.error("Failed to restart Cloudflared service: %s", e)

    def generate_markdown_report(self) -> str:
        """Builds a comprehensive, human-readable markdown audit report."""
        rep = self.report
        ts = rep.get("timestamp_utc", "")
        status = rep.get("overall_status", "UNKNOWN")

        status_badge = (
            "🟢 **ALL SYSTEMS OPERATIONAL (100% HEALTHY)**"
            if status == "ALL_SYSTEMS_OPERATIONAL"
            else "🟡 **SYSTEMS DEGRADED / WARNINGS DETECTED**"
        )

        lines = [
            "# Báo Cáo Kiểm Tra Tự Động Toàn Diện Hệ Thống & Website dinhsonconstruction.com",
            "",
            f"- **Thời gian kiểm tra (UTC):** `{ts}`",
            f"- **Trạng thái tổng thể:** {status_badge}",
            "- **Công ty:** Công ty TNHH Xây Dựng Định Sơn (DSCons - MST: `0202111150`)",
            "",
            "---",
            "",
            "## 1. Trạng Thái Hoạt Động Của Website Công Khai (Cloudflare Edge & Public Domain)",
            "",
            "| URL Kiểm Tra | Phân Hệ / Module | HTTP Status | Độ Trễ (ms) | Dung Lượng | Cloudflare Ray ID | Trạng Thái |",
            "| :--- | :--- | :---: | :---: | :---: | :---: | :---: |",
        ]

        for url, d in rep.get("public_domains", {}).items():
            badge = "✅ Hoạt Động" if d.get("healthy") else "❌ Lỗi"
            code = d.get("status_code", 0)
            latency = d.get("response_time_ms", 0)
            size = d.get("size_bytes", 0)
            cf_ray = d.get("cf_ray", "N/A")
            label = d.get("label", url)
            lines.append(
                f"| [`{url}`]({url}) | **{label}** | `{code}` | `{latency} ms` | `{size:,} B` | `{cf_ray}` | {badge} |"
            )

        lines.extend(
            [
                "",
                "## 2. Trạng Thái Các Dịch Vụ Hệ Thống & Cổng Lắng Nghe (System Services & Ports)",
                "",
                "### A. Cổng Mạng (TCP Ports)",
                "| Cổng | Dịch Vụ / Phân Hệ | Trạng Thái |",
                "| :---: | :--- | :---: |",
            ]
        )

        for p_str, p_data in rep.get("ports", {}).items():
            badge = "✅ MỞ (OPEN)" if p_data.get("open") else "❌ ĐÓNG (CLOSED)"
            desc = p_data.get("description", "")
            lines.append(f"| **`{p_str}`** | {desc} | {badge} |")

        lines.extend(
            [
                "",
                "### B. Dịch Vụ Windows Services",
                "| Tên Dịch Vụ | Trạng Thái Service | Đánh Giá |",
                "| :--- | :---: | :---: |",
            ]
        )

        for s_name, s_data in rep.get("system_services", {}).items():
            badge = (
                "✅ Đang Chạy" if s_data.get("healthy") else "⚠️ Dừng / Không Khả Dụng"
            )
            st_text = s_data.get("status", "Unknown")
            lines.append(f"| **`{s_name}`** | `{st_text}` | {badge} |")

        db_info = rep.get("database", {})
        db_badge = "✅ Kết Nối Tốt" if db_info.get("connected") else "❌ Mất Kết Nối"
        lines.extend(
            [
                "",
                "## 3. Trạng Thái Cơ Sở Dữ Liệu PostgreSQL",
                f"- **Trạng thái:** {db_badge}",
                f"- **Số lượng bảng:** `{db_info.get('table_count', 0)}` bảng",
                f"- **Phiên bản Engine:** `{db_info.get('version', 'N/A')}`",
                "",
                "## 4. Mạng Lưới Phân Tán (Tailscale Mesh & Remote Diagnostics)",
            ]
        )

        ts_info = rep.get("network_mesh", {})
        if ts_info.get("running"):
            self_node = ts_info.get("self", {})
            lines.append(
                f"- **Thiết bị hiện tại (Self):** `{self_node.get('hostname')}` (`{self_node.get('ip')}`) - OS: `{self_node.get('os')}`"
            )
            lines.append("- **Danh sách thiết bị kết nối:**")
            for peer in ts_info.get("peers", []):
                p_online = "🟢 Online" if peer.get("online") else "⚪ Offline"
                port_str = (
                    ", ".join(
                        [
                            f"{k}: {'Mở' if v else 'Đóng'}"
                            for k, v in peer.get("open_ports", {}).items()
                        ]
                    )
                    or "N/A"
                )
                lines.append(
                    f"  - **`{peer.get('hostname')}`** (`{peer.get('ip')}` - {peer.get('os')}): {p_online} (Cổng: `{port_str}`)"
                )
        else:
            lines.append("- **Tailscale:** Chưa chạy hoặc không khả dụng")

        ai_info = rep.get("ai_engines", {})
        lines.extend(
            [
                "",
                "## 5. Dịch Vụ Trí Tuệ Nhân Tạo Cục Bộ (AI Engines)",
                f"- **LM Studio (1234):** {'✅ Online' if ai_info.get('lm_studio', {}).get('available') else '⚪ Không chạy / Offline'}",
                f"- **Ollama (11434):** {'✅ Online' if ai_info.get('ollama', {}).get('available') else '⚪ Không chạy / Offline'}",
            ]
        )

        actions = rep.get("remediation_actions", [])
        lines.extend(
            [
                "",
                "## 6. Lịch Sử Tự Động Khắc Phục Lỗi (Self-Healing Actions)",
            ]
        )
        if actions:
            for act in actions:
                lines.append(f"- 🔧 **Hành động đã thực hiện:** `{act}`")
        else:
            lines.append(
                "- ✨ **Hệ thống hoạt động hoàn hảo, không cần can thiệp phục hồi.**"
            )

        return "\n".join(lines)

    async def run_full_audit(self) -> dict[str, Any]:
        """Runs complete audit lifecycle, executes self-healing if needed, saves logs."""
        logger.info("================================================================")
        logger.info("  STARTING COMPREHENSIVE HEALTH AUDIT FOR DINHSONCONSTRUCTION  ")
        logger.info("================================================================")

        self.report["system_services"] = self.scan_windows_services()
        self.report["ports"] = self.scan_ports()
        self.report["database"] = self.inspect_database()
        self.report["ai_engines"] = await self.inspect_ai_engines()
        self.report["network_mesh"] = self.scan_tailscale()
        self.report["public_domains"] = await self.verify_public_domains()

        # Check if remediation is needed
        has_failure = (
            not self.report["ports"].get("8000", {}).get("open")
            or not self.report["ports"].get("5432", {}).get("open")
            or not self.report["public_domains"]
            .get("https://dinhsonconstruction.com/", {})
            .get("healthy", False)
        )

        if has_failure:
            logger.warning(
                "Detected system failure or unresponsive public endpoints. Initiating self-healing..."
            )
            self.auto_remediate()
            logger.info("Re-verifying post-remediation status...")
            self.report["system_services"] = self.scan_windows_services()
            self.report["ports"] = self.scan_ports()
            self.report["database"] = self.inspect_database()
            self.report["public_domains"] = await self.verify_public_domains()

        # Compute overall status
        core_healthy = (
            self.report["ports"].get("8000", {}).get("open")
            and self.report["ports"].get("5432", {}).get("open")
            and self.report["database"].get("connected")
            and self.report["public_domains"]
            .get("https://dinhsonconstruction.com/", {})
            .get("healthy")
        )
        self.report["overall_status"] = (
            "ALL_SYSTEMS_OPERATIONAL" if core_healthy else "DEGRADED"
        )

        # Save JSON trace files
        timestamp_str = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        historical_json = LOG_DIR / f"system_health_audit_{timestamp_str}.json"
        latest_json = STORAGE_LOG_DIR / "system_health_latest.json"

        with open(historical_json, "w", encoding="utf-8") as f:
            json.dump(self.report, f, ensure_ascii=False, indent=2)

        with open(latest_json, "w", encoding="utf-8") as f:
            json.dump(self.report, f, ensure_ascii=False, indent=2)

        # Generate and save Markdown report
        md_content = self.generate_markdown_report()
        md_file = DOCS_AUDIT_DIR / "system_health_audit_latest.md"
        with open(md_file, "w", encoding="utf-8") as f:
            f.write(md_content)

        logger.info("Trace logs & reports successfully generated:")
        logger.info("  - JSON Trace: %s", historical_json)
        logger.info("  - Latest JSON: %s", latest_json)
        logger.info("  - Markdown Audit: %s", md_file)
        logger.info("================================================================")
        logger.info("Overall Result: %s", self.report["overall_status"])
        return self.report


if __name__ == "__main__":
    auditor = SystemHealthAuditor()
    report = asyncio.run(auditor.run_full_audit())
