#!/usr/bin/env python3
"""
PHT Automated Sales Pipeline - Master Orchestrator
Runs complete flow: Discovery → Enrichment → Personalization → (Ready for Instantly)

Created: March 11, 2026
"""

import sys
import time
from pathlib import Path
from datetime import datetime

# Import pipeline stages
import importlib.util
import os

# Load modules dynamically
def load_module(name, path):
    spec = importlib.util.spec_from_file_location(name, path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

base_dir = Path(__file__).parent
disc = load_module("discovery", base_dir / "1_discovery.py")
enrich = load_module("enrichment", base_dir / "2_enrichment.py")
person = load_module("personalization", base_dir / "3_personalization.py")

# Paths
WORKSPACE = Path("/Users/max/.openclaw/workspace/postharvest")
DATA_DIR = WORKSPACE / "automation" / "data"
DATA_DIR.mkdir(parents=True, exist_ok=True)

def print_banner(stage_name):
    """Print stage banner"""
    print("\n" + "="*60)
    print(f"  {stage_name}")
    print("="*60)

def run_full_pipeline(region="USA", fruit_type="apples", limit=10, test_mode=True):
    """
    Run complete automated pipeline
    
    Args:
        region: Target region
        fruit_type: Target fruit type  
        limit: Number of companies to process
        test_mode: If True, only process 10 companies
    
    Returns:
        Path to final personalized contacts file
    """
    start_time = time.time()
    
    print("\n" + "🚀"*30)
    print(f"  PHT AUTOMATED SALES PIPELINE")
    print(f"  Mode: {'TEST (10 prospects)' if test_mode else 'PRODUCTION'}")
    print(f"  Region: {region}")
    print(f"  Fruit: {fruit_type}")
    print("🚀"*30)
    
    # STAGE 1: DISCOVERY
    print_banner("STAGE 1: DISCOVERY")
    discovery_file = disc.run_discovery(
        region=region,
        fruit_type=fruit_type,
        limit=limit if test_mode else limit,
        test_mode=test_mode
    )
    
    if not discovery_file:
        print("\n❌ Discovery failed - no companies found")
        return None
    
    # STAGE 2: ENRICHMENT
    print_banner("STAGE 2: ENRICHMENT")
    enriched_file = enrich.run_enrichment(discovery_file)
    
    if not enriched_file:
        print("\n❌ Enrichment failed - no contacts found")
        return None
    
    # STAGE 3: PERSONALIZATION
    print_banner("STAGE 3: PERSONALIZATION")
    personalized_file = person.personalize_contacts(enriched_file)
    
    if not personalized_file:
        print("\n❌ Personalization failed")
        return None
    
    # COMPLETE
    elapsed = time.time() - start_time
    print("\n" + "✅"*30)
    print(f"  PIPELINE COMPLETE!")
    print(f"  Time: {elapsed:.1f} seconds")
    print(f"  Output: {personalized_file}")
    print("✅"*30 + "\n")
    
    return personalized_file

def main():
    """Main entry point"""
    
    # Check arguments
    if len(sys.argv) > 1:
        if sys.argv[1] == "test":
            # Test mode: 10 South African citrus companies
            result = run_full_pipeline(
                region="South Africa",
                fruit_type="citrus",
                limit=10,
                test_mode=True
            )
        elif sys.argv[1] == "production":
            # Production mode: 50 companies
            result = run_full_pipeline(
                region="USA",
                fruit_type="apples",
                limit=50,
                test_mode=False
            )
        else:
            print("Usage: python run_pipeline.py [test|production]")
            sys.exit(1)
    else:
        # Default: test mode
        result = run_full_pipeline(
            region="South Africa",
            fruit_type="citrus",
            limit=10,
            test_mode=True
        )
    
    if result:
        print(f"\n📋 Next step:")
        print(f"   Review output: {result}")
        print(f"   Then run: python 4_load_instantly.py {result}")
        print(f"\n   Or update dashboard: python 5_update_dashboard.py")
    else:
        print("\n❌ Pipeline failed")
        sys.exit(1)

if __name__ == "__main__":
    main()
