# orchestrator_text.py

import subprocess
import sys
from pathlib import Path
import argparse
import shutil
import json
from typing import Optional, Dict, List, Union

# --- Configuration ---
PIPELINE_SCRIPTS = [
    "3_design_generator.py", 
    "4_code_generator.py"
]

BASE_OUTPUT_DIR = "../data/website_data"

# Available models
AVAILABLE_MODELS = {
    0: "Gemini 2.5 Pro (GA)",
    1: "Gemini 2.5 Flash (GA)", 
    2: "Gemini 2.5 Flash-Lite (Preview)"
}

# --- MODEL CONFIGURATION ---
MODEL_CONFIG = {
    "design": 0,
    "code": 0
}

def run_step_with_live_output(command: List[str]) -> Optional[Dict[str, Union[float, int]]]:
    """
    Runs a script as a subprocess and captures the final JSON line for cost analysis.
    """
    try:
        import os
        env = os.environ.copy()
        env['PYTHONUNBUFFERED'] = '1'
        
        process = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            encoding='utf-8',
            bufsize=1,
            universal_newlines=True,
            env=env
        )

        last_line = ""
        if process.stdout:
            for line in iter(process.stdout.readline, ''):
                print(line, end='', flush=True)
                last_line = line.strip() if line.strip() else last_line

        process.wait()

        if process.returncode != 0:
            print(f"\n❌ ERROR: Script '{Path(command[1]).name}' failed with exit code {process.returncode}.")
            return None

        try:
            return json.loads(last_line) if last_line else None
        except json.JSONDecodeError:
            return None

    except FileNotFoundError:
        print(f"❌ Error: Could not find script at '{command[1]}'")
        return None
    except Exception as e:
        print(f"❌ An unexpected error occurred: {e}")
        return None

def get_script_command(script_name: str, site_dir: str) -> List[str]:
    """Generate the appropriate command for each script."""
    base_command = [sys.executable, script_name, site_dir]
    if script_name == "3_design_generator.py":
        return base_command + ["--model-index", str(MODEL_CONFIG['design'])]
    elif script_name == "4_code_generator.py":
        return base_command + ["--model-index", str(MODEL_CONFIG['code'])]
    return base_command

def main():
    parser = argparse.ArgumentParser(description="Runs the text-based website generation pipeline.")
    parser.add_argument("--domain", required=True, type=str, help="The domain name for the new site (e.g., company.com).")
    parser.add_argument("--company_name", required=True, type=str, help="The name of the company.")
    parser.add_argument("--site_brief", required=True, type=str, help="A detailed brief about the company and design requirements.")
    
    args = parser.parse_args()

    site_output_dir = Path(BASE_OUTPUT_DIR) / args.domain

    # Create the site directory and initial files
    print(f"🚀 Creating new site for: {args.company_name} ({args.domain})")
    site_output_dir.mkdir(parents=True, exist_ok=True)
    
    # Create a basic manifest.json
    manifest = {"domain": args.domain, "company_name": args.company_name}
    
    # Check if Facebook scraping is needed and extract the URL
    facebook_url = None
    if "FACEBOOK_URL:" in args.site_brief:
        print("📘 Detected Facebook URL in site brief")
        lines = args.site_brief.split('\n')
        for line in lines:
            if line.startswith("FACEBOOK_URL:"):
                facebook_url = line.replace("FACEBOOK_URL:", "").strip()
                break
        
        if facebook_url:
            print(f"🔗 Adding original Facebook URL to manifest: {facebook_url}")
            manifest["site_url"] = facebook_url
    
    # If no Facebook URL found, use the domain as the site_url
    if "site_url" not in manifest:
        manifest["site_url"] = f"https://{args.domain}"
    
    with open(site_output_dir / "manifest.json", "w") as f:
        json.dump(manifest, f, indent=2)

    # Check if Facebook scraping is needed
    processed_site_brief = args.site_brief
    if facebook_url:
        try:
            print(f"🔄 Scraping Facebook page: {facebook_url}")
            # Call the Facebook scraper
            import subprocess
            result = subprocess.run([
                sys.executable, "facebook_scraper.py", facebook_url
            ], capture_output=True, text=True, timeout=300)
            
            if result.returncode == 0:
                # Parse the output to extract formatted text
                output_lines = result.stdout.split('\n')
                formatted_start = -1
                for i, line in enumerate(output_lines):
                    if 'Formatted for orchestrator:' in line:
                        formatted_start = i + 1
                        break
                
                if formatted_start > 0:
                    facebook_content = '\n'.join(output_lines[formatted_start:]).strip()
                    if facebook_content:
                        # Replace the original site brief with Facebook data
                        processed_site_brief = facebook_content
                        print("✅ Successfully extracted Facebook page data for website generation")
                    else:
                        print("⚠️ No formatted content found, using original site brief")
                else:
                    print("⚠️ No formatted content found, using original site brief")
            else:
                print(f"❌ Facebook scraper failed: {result.stderr}")
                print("⚠️ Falling back to original site brief")
        except Exception as e:
            print(f"❌ Error during Facebook scraping: {e}")
            print("⚠️ Falling back to original site brief")

    # Create the site_brief.json from the input with proper structure expected by design generator
    site_brief = {
        "company_name": args.company_name,
        "domain": args.domain,
        "content_brief": processed_site_brief,
        "brand_profile": {
            "brand_identity": args.company_name,
            "business_keywords": ["business", "professional", "service"],
            "colors": [
                {"name": "Primary Blue", "hex": "#007bff"},
                {"name": "Secondary Gray", "hex": "#6c757d"},
                {"name": "Success Green", "hex": "#28a745"},
                {"name": "Dark Text", "hex": "#333333"}
            ],
            "typography": {
                "primary_font": "Inter",
                "secondary_font": "system-ui",
                "styles": ["clean", "modern", "readable"]
            },
            "design_style": "Clean, modern, and professional design suitable for business websites",
            "logo_description": f"Modern text-based logo for {args.company_name}",
            "visual_elements": ["clean lines", "professional layout", "modern typography"]
        },
        "navigation_links": [
            {"text": "Home", "href": "#home"},
            {"text": "About", "href": "#about"},
            {"text": "Services", "href": "#services"},
            {"text": "Contact", "href": "#contact"}
        ],
        "site_metadata": {
            "site_title": args.company_name,
            "primary_domain": args.domain,
            "meta_description": f"Professional website for {args.company_name}"
        },
        "site_pages": [
            {
                "page_key": "home",
                "title": "Home",
                "url": "/",
                "content_sections": {
                    "hero": f"Welcome to {args.company_name}",
                    "about": processed_site_brief,
                    "services": "Our professional services and offerings",
                    "contact": "Get in touch with us today"
                }
            },
            {
                "page_key": "about",
                "title": "About Us",
                "url": "/about",
                "content_sections": {
                    "main_content": processed_site_brief
                }
            },
            {
                "page_key": "contact",
                "title": "Contact",
                "url": "/contact",
                "content_sections": {
                    "contact_info": "Contact information and details"
                }
            }
        ]
    }
    with open(site_output_dir / "site_brief.json", "w") as f:
        json.dump(site_brief, f, indent=2)
        
    print(f"✅ Created manifest and site brief for {args.domain}")

    total_pipeline_cost = 0.0

    print(f"🤖 Model Configuration:")
    print(f"   - Design Generation: {AVAILABLE_MODELS[MODEL_CONFIG['design']]}")
    print(f"   - Code Generation: {AVAILABLE_MODELS[MODEL_CONFIG['code']]}")
    print()

    for step_num, script_name in enumerate(PIPELINE_SCRIPTS, 1):
        print(f"\n--- STEP {step_num} of {len(PIPELINE_SCRIPTS)}: {script_name} ---")
        
        command = get_script_command(script_name, str(site_output_dir))
        usage = run_step_with_live_output(command)
        
        if usage is None:
            print(f"   Stopping pipeline for {args.domain} due to error in {script_name}")
            break
        
        script_cost = usage.get("cost", 0)
        total_pipeline_cost += script_cost
        
        if script_cost > 0:
            print(f"   💰 Step cost: ${script_cost:.6f}")

    else:
        print(f"\n✔️ Pipeline completed successfully for: {args.domain}")
    
    print(f"\n💰 Total Estimated Cost: ${total_pipeline_cost:.6f}")

if __name__ == "__main__":
    main() 