#!/usr/bin/env python3
"""
Script to add error handler imports and wrappers to all Supabase Edge Functions
"""

import os
import re

# List of functions to update (excluding ones already done)
FUNCTIONS_TO_UPDATE = [
    "oauth-shoprenter-callback",
    "webhooks-shopify",
    "webhook-shoprenter-uninstall",
    "trigger-sync",
    "shopify-sync",
    "woocommerce-sync",
    "shoprenter-sync",
    "shoprenter-scheduled-sync",
    "woocommerce-scheduled-sync",
    "shoprenter-products",
    "shoprenter-orders",
    "shoprenter-customers",
    "get-ai-context",
]

BASE_PATH = "/home/claude/shopcall/supabase/functions"

def update_function_file(func_name):
    file_path = os.path.join(BASE_PATH, func_name, "index.ts")

    if not os.path.exists(file_path):
        print(f"❌ File not found: {file_path}")
        return False

    with open(file_path, 'r') as f:
        content = f.read()

    # Check if already updated
    if "from '../_shared/error-handler.ts'" in content:
        print(f"⏭️  {func_name}: Already has error handler, skipping")
        return True

    # Add import after supabase-js import
    import_pattern = r"(import.*from.*supabase-js.*\n)"
    import_replacement = r"\1import { wrapHandler, logError } from '../_shared/error-handler.ts'\n"
    content = re.sub(import_pattern, import_replacement, content, count=1)

    # Wrap the serve handler
    # Pattern: serve(async (req) => {
    # Replace with: serve(wrapHandler('function-name', async (req) => {
    serve_pattern = r"serve\(async \(req\) => \{"
    serve_replacement = f"serve(wrapHandler('{func_name}', async (req) => {{"
    content = re.sub(serve_pattern, serve_replacement, content, count=1)

    # Remove outer try-catch block
    # Find the last occurrence of } catch (error) { before the final })
    # This is tricky, so we'll use a simpler approach:
    # Find lines with "  } catch (error) {" near the end and remove them
    # along with their corresponding error handling and closing }

    lines = content.split('\n')
    modified_lines = []
    skip_until_closing = False
    brace_depth = 0
    found_catch = False

    for i, line in enumerate(lines):
        # Check if this is the outer catch block (usually indented with 2 spaces)
        if re.match(r'^  } catch \(error\).*\{$', line) and i > len(lines) - 30:
            skip_until_closing = True
            found_catch = True
            brace_depth = 1
            continue

        if skip_until_closing:
            # Count braces to find the end of catch block
            brace_depth += line.count('{') - line.count('}')
            if brace_depth == 0:
                skip_until_closing = False
                # Skip this closing brace line
                continue
            continue

        modified_lines.append(line)

    # If we found a catch block, we need to add an extra closing paren
    if found_catch:
        # The last line should be just })
        # We need to change it to }))
        if modified_lines and modified_lines[-1].strip() == '})':
            modified_lines[-1] = modified_lines[-1].replace('})', '))')

    content = '\n'.join(modified_lines)

    # Write back
    with open(file_path, 'w') as f:
        f.write(content)

    print(f"✅ {func_name}: Updated successfully")
    return True

def main():
    print("Starting Edge Function updates...")
    print("=" * 60)

    success_count = 0
    for func_name in FUNCTIONS_TO_UPDATE:
        if update_function_file(func_name):
            success_count += 1
        print()

    print("=" * 60)
    print(f"Completed: {success_count}/{len(FUNCTIONS_TO_UPDATE)} functions updated")

if __name__ == "__main__":
    main()
