import os
import re
from pathlib import Path

# Mocking Colors for terminal output
class Colors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'

def print_banner():
    print(f"\n{Colors.BOLD}{Colors.OKBLUE}{'='*60}{Colors.ENDC}")
    print(f"{Colors.BOLD}{Colors.OKBLUE}{'🧬 OPENAPI SYNC BRIDGE v1.0'.center(60)}{Colors.ENDC}")
    print(f"{Colors.BOLD}{Colors.OKBLUE}{'='*60}{Colors.ENDC}\n")

def scan_backend_routes(backend_dir):
    """Simple regex scanner for FastAPI/Express style routes."""
    print(f"[*] Scanning {backend_dir} for API contracts...")
    routes = []
    # This is a simplified demo scanner
    for root, _, files in os.walk(backend_dir):
        for file in files:
            if file.endswith(('.js', '.py')):
                path = Path(root) / file
                content = path.read_text(encoding='utf-8')
                # Find @app.get('/path') or router.get('/path')
                matches = re.findall(r"(?:app|router|route)\.(get|post|put|delete)\(['\"]([^'\"]+)['\"]", content)
                for method, url in matches:
                    routes.append({"method": method.upper(), "url": url, "source": path.name})
    return routes

def generate_frontend_stubs(routes, target_file):
    """Generate a TypeScript interface file based on discovered routes."""
    print(f"[*] Generating Type-Safe stubs in {target_file}...")
    stub_content = ["// 🧬 AUTO-GENERATED API CONTRACTS", "// Generated by sync_api_contracts.py\n"]
    stub_content.append("export const API_ENDPOINTS = {")
    for r in routes:
        name = r['url'].strip('/').replace('/', '_').upper() or "ROOT"
        stub_content.append(f"  {name}: {{ method: '{r['method']}', url: '{r['url']}' }}, // from {r['source']}")
    stub_content.append("};")
    
    Path(target_file).parent.mkdir(parents=True, exist_ok=True)
    Path(target_file).write_text("\n".join(stub_content), encoding='utf-8')

def main():
    print_banner()
    backend = "src/backend"
    frontend_stub = "src/frontend/generated/api-contracts.ts"
    
    # Run Sync
    if not os.path.exists(backend):
        print(f"{Colors.WARNING}[!] Backend directory not found. Using defaults.{Colors.ENDC}")
        routes = [{"method": "GET", "url": "/health", "source": "core.py"}]
    else:
        routes = scan_backend_routes(backend)
    
    generate_frontend_stubs(routes, frontend_stub)
    print(f"\n{Colors.OKGREEN}✅ SYNC COMPLETE: {len(routes)} contracts bridged to frontend.{Colors.ENDC}")

if __name__ == "__main__":
    main()
