#!/usr/bin/env python3
"""Aura Health Audit — lightweight check for unwired routes, untested services, portability violations."""
import os, re, glob

RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
RESET = "\033[0m"
BOLD = "\033[1m"

def get_services():
    return sorted([
        os.path.splitext(os.path.basename(f))[0]
        for f in glob.glob("app/services/*.py")
        if "__" not in f
    ])

def get_tested_services():
    tested = set()
    for f in glob.glob("tests/test_*.py"):
        name = os.path.splitext(os.path.basename(f))[0].replace("test_", "")
        tested.add(name)
    alias_map = {
        "brandkit_dedup": "brandkit", "brandkit_upload": "brandkit",
        "llm_injection": "llm", "llm_routing": "llm",
        "api_marketplace": "marketplace", "api_routing": "llm",
        "api_auth": "auth", "api_health": "health",
    }
    for test_name, svc in alias_map.items():
        if test_name in tested:
            tested.add(svc)
    return tested

def check_portability(service_file):
    issues = []
    with open(service_file) as f:
        content = f.read()
    hardcoded = re.findall(r'os\.environ\.get\(["\']AI_INTEGRATIONS_\w+["\'](?!\s*,)', content)
    if hardcoded and "_resolve_env" not in content:
        issues.append(f"Hardcoded Replit env var without fallback: {hardcoded[0]}")
    return issues

def check_routes():
    with open("app/main.py") as f:
        content = f.read()
    routes = re.findall(r'@app\.(get|post|put|delete)\("([^"]+)"', content)
    return [(method.upper(), path) for method, path in routes]

def main():
    print(f"\n{BOLD}=== AURA HEALTH AUDIT ==={RESET}\n")

    services = get_services()
    tested = get_tested_services()

    print(f"{BOLD}Services ({len(services)}):{RESET}")
    untested = []
    for s in services:
        has_test = s in tested or f"api_{s}" in tested
        icon = f"{GREEN}✓{RESET}" if has_test else f"{RED}✗{RESET}"
        print(f"  {icon} {s}")
        if not has_test:
            untested.append(s)

    print(f"\n{BOLD}Portability Check:{RESET}")
    for s in services:
        path = f"app/services/{s}.py"
        issues = check_portability(path)
        if issues:
            for issue in issues:
                print(f"  {YELLOW}⚠{RESET} {s}: {issue}")

    if not any(check_portability(f"app/services/{s}.py") for s in services):
        print(f"  {GREEN}✓ All services pass portability check{RESET}")

    routes = check_routes()
    templates = glob.glob("app/templates/*.html")
    tests = glob.glob("tests/test_*.py")

    print(f"\n{BOLD}Summary:{RESET}")
    print(f"  Routes: {len(routes)}")
    print(f"  Templates: {len(templates)}")
    print(f"  Test files: {len(tests)}")
    print(f"  Untested services: {len(untested)} — {', '.join(untested) if untested else 'none'}")

    if untested:
        print(f"\n{YELLOW}Action needed: {len(untested)} services without test coverage{RESET}")
    else:
        print(f"\n{GREEN}All services have test coverage{RESET}")

    print()

if __name__ == "__main__":
    main()
