#!/usr/bin/env python3
"""
Demo Research Skill - Main execution script

This script creates a complete notebook-style data analysis page for US electricity energy.
It generates JSON data from DuckDB, creates the React page component, adds the route,
and verifies the page works.

Usage:
    python Skills/demo-research/scripts/run-skill.py
"""

import os
import sys
import json
import shutil
import subprocess
from pathlib import Path

# Paths
WORKSPACE = Path("/home/workspace")
RESEARCH_DIR = WORKSPACE / "research/usa_energy"
WEB_SCRATCH = WORKSPACE / "web/scratch"
DATA_DIR = WEB_SCRATCH / "src/data/usa_energy"
PAGES_DIR = WEB_SCRATCH / "src/pages"
APP_TSX = WEB_SCRATCH / "src/App.tsx"

# Colors for terminal output
GREEN = "\033[92m"
BLUE = "\033[94m"
YELLOW = "\033[93m"
RED = "\033[91m"
RESET = "\033[0m"


def log(message, color=BLUE):
    """Print a colored message."""
    print(f"{color}{message}{RESET}")


def check_prerequisites():
    """Check that required files and directories exist."""
    log("Checking prerequisites...", BLUE)
    
    # Check research directory
    if not RESEARCH_DIR.exists():
        log(f"ERROR: Research directory not found: {RESEARCH_DIR}", RED)
        log("Please ensure research/usa_energy exists with usa_electricity.duckdb", RED)
        return False
    
    # Check DuckDB database
    db_path = RESEARCH_DIR / "usa_electricity.duckdb"
    if not db_path.exists():
        log(f"ERROR: DuckDB database not found: {db_path}", RED)
        return False
    
    # Check web/scratch directory
    if not WEB_SCRATCH.exists():
        log(f"ERROR: web/scratch directory not found: {WEB_SCRATCH}", RED)
        return False
    
    log("✓ All prerequisites met", GREEN)
    return True


def generate_json_data():
    """Generate JSON data files from DuckDB."""
    log("\nGenerating JSON data from DuckDB...", BLUE)
    
    # Create data directory
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    
    # Run the generation script
    script_path = WORKSPACE / "Skills/demo-research/scripts/generate-story-json.py"
    output_path = DATA_DIR / "energy_story.json"
    
    result = subprocess.run(
        [sys.executable, str(script_path), str(RESEARCH_DIR / "usa_electricity.duckdb"), str(output_path)],
        capture_output=True,
        text=True
    )
    
    if result.returncode != 0:
        log(f"ERROR: Failed to generate JSON data", RED)
        log(result.stderr, RED)
        return False
    
    log(f"✓ Generated {output_path}", GREEN)
    
    # Generate regional data
    regional_output = DATA_DIR / "regional_data.json"
    result = subprocess.run(
        [sys.executable, str(script_path), str(RESEARCH_DIR / "usa_electricity.duckdb"), str(regional_output), "--regional"],
        capture_output=True,
        text=True
    )
    
    if result.returncode != 0:
        log(f"WARNING: Failed to generate regional data (optional)", YELLOW)
    else:
        log(f"✓ Generated {regional_output}", GREEN)
    
    return True


def create_page_component():
    """Create the React page component."""
    log("\nCreating React page component...", BLUE)
    
    # Read the template
    template_path = WORKSPACE / "Skills/demo-research/assets/UsaEnergyTemplate.tsx"
    if not template_path.exists():
        log(f"ERROR: Template not found: {template_path}", RED)
        return False
    
    template_content = template_path.read_text()
    
    # Write the page component
    page_path = PAGES_DIR / "UsaEnergy.tsx"
    page_path.write_text(template_content)
    
    log(f"✓ Created {page_path}", GREEN)
    return True


def add_route():
    """Add the route to App.tsx."""
    log("\nAdding route to App.tsx...", BLUE)
    
    if not APP_TSX.exists():
        log(f"ERROR: App.tsx not found: {APP_TSX}", RED)
        return False
    
    app_content = APP_TSX.read_text()
    
    # Check if route already exists
    if 'UsaEnergy' in app_content and 'path="/usa-energy"' in app_content:
        log("✓ Route already exists in App.tsx", GREEN)
        return True
    
    # Find the import section and add import
    import_line = 'import UsaEnergy from "./pages/UsaEnergy";'
    if import_line not in app_content:
        # Find the last import line
        lines = app_content.split('\n')
        last_import_idx = -1
        for i, line in enumerate(lines):
            if line.strip().startswith('import ') and 'from' in line:
                last_import_idx = i
        
        if last_import_idx >= 0:
            lines.insert(last_import_idx + 1, import_line)
            app_content = '\n'.join(lines)
    
    # Find the Routes section and add the route
    route_line = '        <Route path="/usa-energy" element={<UsaEnergy />} />'
    if route_line not in app_content:
        # Find the closing </Routes> tag
        lines = app_content.split('\n')
        routes_idx = -1
        for i, line in enumerate(lines):
            if '</Routes>' in line:
                routes_idx = i
                break
        
        if routes_idx >= 0:
            lines.insert(routes_idx, route_line)
            app_content = '\n'.join(lines)
    
    # Write back
    APP_TSX.write_text(app_content)
    log("✓ Added route to App.tsx", GREEN)
    return True


def verify_page():
    """Verify the page is accessible."""
    log("\nVerifying page...", BLUE)
    
    # Check that all files exist
    files_to_check = [
        DATA_DIR / "energy_story.json",
        PAGES_DIR / "UsaEnergy.tsx",
    ]
    
    all_exist = True
    for file_path in files_to_check:
        if file_path.exists():
            log(f"✓ {file_path}", GREEN)
        else:
            log(f"✗ {file_path} not found", RED)
            all_exist = False
    
    if all_exist:
        log("\n" + "="*60, GREEN)
        log("SUCCESS! Page created successfully.", GREEN)
        log("="*60, GREEN)
        log("\nThe US Energy page is now available at:", BLUE)
        log("  /usa-energy", BLUE)
        log("\nView it in your browser at the web/scratch site.", BLUE)
        return True
    else:
        log("\nERROR: Some files are missing", RED)
        return False


def main():
    """Main execution function."""
    log("="*60, BLUE)
    log("Demo Research Skill - US Energy Page Generator", BLUE)
    log("="*60, BLUE)
    
    # Check prerequisites
    if not check_prerequisites():
        sys.exit(1)
    
    # Generate JSON data
    if not generate_json_data():
        sys.exit(1)
    
    # Create page component
    if not create_page_component():
        sys.exit(1)
    
    # Add route
    if not add_route():
        sys.exit(1)
    
    # Verify
    if not verify_page():
        sys.exit(1)
    
    log("\nDone!", GREEN)


if __name__ == "__main__":
    main()