#!/usr/bin/env python3
"""
Automated endpoint extraction and router generation script.
This script reads main.py and generates complete router files.
"""

import re
import os
from pathlib import Path

def extract_endpoint_function(content, endpoint_decorator):
    """
    Extract the complete function code for an endpoint.
    Finds the decorator and extracts everything until the next @app decorator or end of file.
    """
    # Find the decorator position
    start = content.find(endpoint_decorator)
    if start == -1:
        return None
    
    # Find the next @app decorator or end of imports section
    next_endpoint = content.find('\n@app.', start + len(endpoint_decorator))
    next_section = content.find('\n# ===', start + len(endpoint_decorator))
    
    # Use whichever comes first
    if next_endpoint == -1 and next_section == -1:
        end = len(content)
    elif next_endpoint == -1:
        end = next_section
    elif next_section == -1:
        end = next_endpoint
    else:
        end = min(next_endpoint, next_section)
    
    return content[start:end].strip()

def generate_router_file(router_name, endpoints, has_models=False):
    """Generate a complete router file with all endpoints"""
    
    # Base imports
    imports = f'''"""
{router_name.replace('_', ' ').title()} router.
Auto-generated from main.py migration.
"""
from fastapi import APIRouter, HTTPException, Depends, status
from fastapi.security import HTTPAuthorizationCredentials
from typing import Optional, Dict, Any
from datetime import datetime
import random
import json
import logging

from ..core.security import get_current_user, security, verify_internal_key
from ..services.models import *
from ..services.helpers import calculate_distance, calculate_stamina_cost, calculate_player_capacity
from .. import database as db
from ..items import ItemsManager
from .. import game_logic
from ..core.websockets import manager

logger = logging.getLogger(__name__)

# These will be injected by main.py
LOCATIONS = None
ITEMS_MANAGER = None
WORLD = None

def init_router_dependencies(locations, items_manager, world):
    """Initialize router with game data dependencies"""
    global LOCATIONS, ITEMS_MANAGER, WORLD
    LOCATIONS = locations
    ITEMS_MANAGER = items_manager
    WORLD = world

router = APIRouter(tags=["{router_name}"])

'''
    
    # Add endpoints
    router_content = imports + "\n\n# Endpoints\n\n" + "\n\n\n".join(endpoints)
    
    return router_content

def main():
    # Read main.py
    main_path = Path('main.py')
    if not main_path.exists():
        print("ERROR: main.py not found!")
        return
    
    content = main_path.read_text()
    
    # Define endpoint groups
    endpoint_groups = {
        'game_routes': [
            '@app.get("/api/game/state")',
            '@app.get("/api/game/profile")',
            '@app.post("/api/game/spend_point")',
            '@app.get("/api/game/location")',
            '@app.post("/api/game/move")',
            '@app.post("/api/game/inspect")',
            '@app.post("/api/game/interact")',
            '@app.post("/api/game/use_item")',
            '@app.post("/api/game/pickup")',
            '@app.get("/api/game/inventory")',
            '@app.post("/api/game/item/drop")',
        ],
        'equipment': [
            '@app.post("/api/game/equip")',
            '@app.post("/api/game/unequip")',
            '@app.get("/api/game/equipment")',
            '@app.post("/api/game/repair_item")',
            '@app.get("/api/game/repairable")',
            '@app.get("/api/game/salvageable")',
        ],
        'crafting': [
            '@app.get("/api/game/craftable")',
            '@app.post("/api/game/craft_item")',
            '@app.post("/api/game/uncraft_item")',
        ],
        'loot': [
            '@app.get("/api/game/corpse/{corpse_id}")',
            '@app.post("/api/game/loot_corpse")',
        ],
        'combat': [
            '@app.get("/api/game/combat")',
            '@app.post("/api/game/combat/initiate")',
            '@app.post("/api/game/combat/action")',
            '@app.post("/api/game/pvp/initiate")',
            '@app.get("/api/game/pvp/status")',
            '@app.post("/api/game/pvp/acknowledge")',
            '@app.post("/api/game/pvp/action")',
        ],
        'statistics': [
            '@app.get("/api/statistics/{player_id}")',
            '@app.get("/api/statistics/me")',
            '@app.get("/api/leaderboard/{stat_name}")',
        ],
    }
    
    # Process each group
    for router_name, decorators in endpoint_groups.items():
        print(f"\nProcessing {router_name}...")
        endpoints = []
        
        for decorator in decorators:
            func_code = extract_endpoint_function(content, decorator)
            if func_code:
                # Replace @app with @router
                func_code = func_code.replace('@app.', '@router.')
                endpoints.append(func_code)
                print(f"  ✓ Extracted: {decorator}")
            else:
                print(f"  ✗ Not found: {decorator}")
        
        if endpoints:
            router_content = generate_router_file(router_name, endpoints)
            output_path = Path(f'routers/{router_name}.py')
            output_path.write_text(router_content)
            print(f"  ✅ Created routers/{router_name}.py with {len(endpoints)} endpoints")
        else:
            print(f"  ⚠️  No endpoints found for {router_name}")
    
    print("\n" + "="*60)
    print("Router generation complete!")
    print("Next step: Create new streamlined main.py")

if __name__ == "__main__":
    main()
