#!/usr/bin/env python3
"""
Aplicar padrão hybrid auth em TODOS os endpoints restantes
"""

import os
import re
from pathlib import Path

FUNCTIONS_DIR = Path("supabase/functions")

# Endpoints que precisam de auth
ENDPOINTS_WITH_AUTH = [
    "user-update-preferences",
    "appointments-create",
    "appointments-update",
    "appointments-cancel",
    "patients-history",
    "patients-preferences",
    "patients-portal",
    "waitlist-remove",
    "waitlist-match",
    "exceptions-create",
    "exceptions-delete",
    "exceptions-list",
    "doctor-occupancy",
    "doctor-delay-suggestion",
    "audit-list",
    "analytics-heatmap",
    "analytics-demand-curve",
    "analytics-ranking-reasons",
    "analytics-monthly-no-show",
    "analytics-specialty-heatmap",
    "analytics-custom-report",
    "reports-list-extended",
    "reports-export-csv",
    "reports-integrity-check",
    "notifications-subscription",
    "queue-checkin",
    "system-health-check",
    "system-cache-rebuild",
    "system-cron-runner",
    "accessibility-preferences",
]

def update_endpoint(endpoint_name):
    index_file = FUNCTIONS_DIR / endpoint_name / "index.ts"
    
    if not index_file.exists():
        print(f"⚠️  {endpoint_name} - File not found")
        return False
    
    content = index_file.read_text()
    
    # Verificar se já foi atualizado
    if "validateExternalAuth" in content or "x-external-jwt" in content:
        print(f"✓ {endpoint_name} - Already updated")
        return True
    
    # Verificar se tem auth para substituir
    if "auth.getUser()" not in content:
        print(f"⊘ {endpoint_name} - No auth pattern")
        return False
    
    print(f"🔄 {endpoint_name} - Updating...")
    
    # 1. Adicionar/substituir import
    if 'import { createClient } from "https://esm.sh/@supabase/supabase-js@2";' in content:
        content = content.replace(
            'import { createClient } from "https://esm.sh/@supabase/supabase-js@2";',
            'import { validateExternalAuth } from "../_shared/auth.ts";'
        )
    elif 'import { corsHeaders } from "../_shared/cors.ts";' in content:
        content = content.replace(
            'import { corsHeaders } from "../_shared/cors.ts";',
            'import { corsHeaders } from "../_shared/cors.ts";\nimport { validateExternalAuth } from "../_shared/auth.ts";'
        )
    
    # 2. Substituir padrão de autenticação
    # Pattern 1: com authHeader
    pattern1 = r'const authHeader = req\.headers\.get\("Authorization"\);?\s*(if \(!authHeader\)[^}]*\})?\s*const supabase = createClient\([^)]+,[^)]+,\s*\{ global: \{ headers: \{ Authorization: authHeader[^}]*\}[^)]*\);?\s*const \{ data: \{ user \}[^}]*\} = await supabase\.auth\.getUser\(\);?\s*(if \([^)]*authError[^}]*\{[^}]*\})?'
    
    replacement1 = '''const { user, ownSupabase } = await validateExternalAuth(req);
    const supabase = ownSupabase;'''
    
    content = re.sub(pattern1, replacement1, content, flags=re.MULTILINE | re.DOTALL)
    
    # Salvar
    index_file.write_text(content)
    print(f"✅ {endpoint_name}")
    return True

def main():
    print("=== BULK UPDATE: HYBRID AUTH ===\n")
    
    updated = 0
    skipped = 0
    
    for endpoint in ENDPOINTS_WITH_AUTH:
        if update_endpoint(endpoint):
            updated += 1
        else:
            skipped += 1
    
    print(f"\n=== SUMMARY ===")
    print(f"✅ Updated: {updated}")
    print(f"⊘ Skipped: {skipped}")
    print(f"\nNext: pnpx supabase functions deploy")

if __name__ == "__main__":
    main()
