#!/usr/bin/env python3
"""Remove all console.log statements from frontend files, handling multi-line."""
import re
import sys
import os

def remove_console_logs(filepath):
    with open(filepath, 'r') as f:
        content = f.read()
    
    original = content
    removed = 0
    
    # Strategy: find 'console.log(' and track parentheses to find the full statement
    result = []
    i = 0
    lines = content.split('\n')
    
    while i < len(lines):
        line = lines[i]
        stripped = line.strip()
        
        # Check if this line contains console.log(
        if 'console.log(' in stripped:
            # Check if the statement is complete on this line (balanced parens)
            log_start = line.find('console.log(')
            # Count from the opening paren of console.log(
            paren_count = 0
            found_start = False
            complete = False
            
            for ch in stripped[stripped.find('console.log('):]:
                if ch == '(':
                    paren_count += 1
                    found_start = True
                elif ch == ')':
                    paren_count -= 1
                    if found_start and paren_count == 0:
                        complete = True
                        break
            
            if complete:
                # Single line console.log - remove the entire line
                # But check if there's other code on the same line before console.log
                before_log = line[:line.find('console.log(')].rstrip()
                if before_log and not before_log.isspace():
                    # There's code before console.log on same line - keep the before part
                    result.append(before_log)
                # Skip this line entirely
                removed += 1
                i += 1
                continue
            else:
                # Multi-line console.log - skip lines until parens balance
                multi_lines = [line]
                j = i + 1
                total_content = stripped[stripped.find('console.log('):]
                
                while j < len(lines) and paren_count > 0:
                    total_content += '\n' + lines[j]
                    for ch in lines[j]:
                        if ch == '(':
                            paren_count += 1
                        elif ch == ')':
                            paren_count -= 1
                            if paren_count == 0:
                                break
                    multi_lines.append(lines[j])
                    j += 1
                
                # Check if there's code before console.log on the first line
                before_log = line[:line.find('console.log(')].rstrip()
                if before_log and not before_log.isspace():
                    result.append(before_log)
                
                removed += 1
                i = j
                continue
        
        result.append(line)
        i += 1
    
    new_content = '\n'.join(result)
    
    if removed > 0:
        with open(filepath, 'w') as f:
            f.write(new_content)
        print(f"  ✅ {filepath}: removed {removed} console.log statements")
    else:
        print(f"  ⏭️  {filepath}: no console.log found")
    
    return removed

# Frontend files to clean
base = os.path.dirname(os.path.abspath(__file__))
src = os.path.join(base, 'src', 'routes')

frontend_files = [
    'src/routes/(dashboard)/dashboard/map/+page.svelte',
    'src/routes/(dashboard)/dashboard/campaigns/new/+page.svelte',
    'src/routes/(dashboard)/dashboard/map/embed/+page.svelte',
    'src/routes/(dashboard)/dashboard/media/+page.svelte',
    'src/routes/(dashboard)/dashboard/ads/[id]/edit/+page.svelte',
    'src/routes/(admin)/admin/settings/+page.svelte',
    'src/routes/(agency)/agency/map/+page.svelte',
    'src/routes/(advertiser)/advertiser/map/+page.svelte',
]

total = 0
for f in frontend_files:
    full = os.path.join(base, f)
    if os.path.exists(full):
        total += remove_console_logs(full)
    else:
        print(f"  ⚠️  {f}: file not found")

print(f"\nTotal: {total} console.log statements removed from {len(frontend_files)} files")
