import socket
import ssl
import subprocess
import time
import urllib.error
import urllib.request


def run_cmd(cmd):
    try:
        res = subprocess.run(cmd, capture_output=True, text=True, shell=True)
        return res.stdout.strip()
    except Exception as e:
        return f"Error: {e}"


def main():
    print("==================================================")
    print("   DSCons SYSTEM & WEBSITE HEALTH DIAGNOSTICS     ")
    print("   Time:", time.strftime("%Y-%m-%d %H:%M:%S"))
    print("==================================================")

    print("\n[1] CHECKING RUNNING PROCESSES:")
    ps_cmd = "powershell -NoProfile -Command \"Get-CimInstance Win32_Process | Where-Object { $_.Name -match 'python|cloudflared|nginx|caddy|node' } | Select-Object ProcessId, Name, CommandLine | Format-List\""
    print(run_cmd(ps_cmd))

    print("\n[2] CHECKING LISTENING PORTS (8000, 80, 443, 22, 5432, 11434):")
    netstat_cmd = 'netstat -ano | findstr "LISTENING"'
    netstat_out = run_cmd(netstat_cmd)
    for line in netstat_out.splitlines():
        if any(
            f":{p} " in line or f":{p}\t" in line
            for p in [8000, 80, 443, 22, 5432, 11434]
        ):
            print("  ", line)

    print("\n[3] CHECKING TAILSCALE STATUS:")
    print(run_cmd("tailscale status"))

    print("\n[4] CHECKING CLOUDFLARED CONFIG / SERVICE:")
    cf_svc = run_cmd(
        'powershell -NoProfile -Command "Get-Service cloudflared -ErrorAction SilentlyContinue | Format-List"'
    )
    print(
        cf_svc
        if cf_svc
        else "No cloudflared Windows service found, checking process..."
    )

    print("\n[5] CHECKING DNS RESOLUTION:")
    try:
        ips = socket.gethostbyname_ex("dinhsonconstruction.com")
        print(f"  DNS for dinhsonconstruction.com: {ips}")
    except Exception as e:
        print(f"  DNS resolution failed: {e}")

    print("\n[6] CHECKING LOCAL BACKEND (http://127.0.0.1:8000):")
    endpoints = ["/", "/api/v1/health", "/docs", "/login", "/dashboard"]
    for ep in endpoints:
        url = f"http://127.0.0.1:8000{ep}"
        try:
            req = urllib.request.Request(url, headers={"User-Agent": "HealthCheck/1.0"})
            with urllib.request.urlopen(req, timeout=5) as resp:
                print(
                    f"  [OK] {url} -> Status: {resp.status}, Content-Length: {len(resp.read())}"
                )
        except urllib.error.HTTPError as e:
            print(f"  [HTTP {e.code}] {url} -> {e.reason}")
        except Exception as e:
            print(f"  [FAILED] {url} -> {e}")

    print("\n[7] CHECKING PUBLIC DOMAIN (https://dinhsonconstruction.com):")
    domain_urls = [
        "https://dinhsonconstruction.com",
        "https://dinhsonconstruction.com/login",
        "https://dinhsonconstruction.com/dashboard",
        "https://dinhsonconstruction.com/api/v1/health",
    ]
    ctx = ssl.create_default_context()
    for url in domain_urls:
        try:
            req = urllib.request.Request(
                url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
            )
            with urllib.request.urlopen(req, context=ctx, timeout=8) as resp:
                body = resp.read()
                print(f"  [OK] {url} -> Status: {resp.status}, Length: {len(body)}")
        except urllib.error.HTTPError as e:
            print(f"  [HTTP {e.code}] {url} -> {e.reason}")
        except Exception as e:
            print(f"  [FAILED] {url} -> {e}")

    print("\n==================================================")


if __name__ == "__main__":
    main()
