#!/usr/bin/env python3
"""
Genesis Batch Gift Factory
==========================
Automates the mass-generation of "Perfect Entry" assets for the Alpha Strike mission.
Targets: Sydney/Melbourne Emergency Tradies.
"""

import sys
import os
import csv
import json
import asyncio
from pathlib import Path
from typing import List, Dict, Any

# Add genesis path
GENESIS_ROOT = Path(__file__).parent.parent.parent
sys.path.insert(0, str(GENESIS_ROOT))

from core.gemini_executor import GeminiExecutor
from revenue.engine import UnifiedGiftFactory
from core.revenue.provisioning_engine import RevenueProvisioningEngine

class BatchGiftGenerator:
    def __init__(self):
        self.executor = GeminiExecutor(use_rate_maximizer=True)
        self.factory = UnifiedGiftFactory(self.executor)
        self.provisioner = RevenueProvisioningEngine()
        self.output_dir = GENESIS_ROOT / "revenue" / "data" / "batches"
        self.output_dir.mkdir(exist_ok=True, parents=True)

    def extract_top_leads(self, csv_path: str, limit: int = 50) -> List[Dict[str, Any]]:
        """Filters the CSV for high-value Sydney/Melbourne plumber/locksmith leads."""
        leads = []
        with open(csv_path, mode='r', encoding='utf-8') as f:
            reader = csv.DictReader(f)
            for row in reader:
                industry = row.get("Industry", "").lower()
                state = row.get("State", "").lower()
                description = row.get("Description", "")
                
                # Target: Plumbing/Locksmith in NSW/VIC
                if ("plumber" in industry or "locksmith" in industry) and \
                   ("new south wales" in state or "nsw" in state or "victoria" in state or "vic" in state):
                    
                    # Basic high-intent filtering (Rating > 4.5 in description)
                    if "Rating: 4." in description or "Rating: 5" in description:
                        leads.append(row)
                
                if len(leads) >= limit:
                    break
        return leads

    async def run_batch(self, leads: List[Dict[str, Any]], batch_name: str):
        """Generates the Perfect Entry assets for the provided leads."""
        results = []
        print(f"🚀 Starting Batch: {batch_name} ({len(leads)} leads)")
        
        for lead in leads:
            biz_name = lead.get("Company", "Valued Business")
            niche = lead.get("Industry", "Tradie")
            
            print(f"  > Generating asset for: {biz_name}...")
            # We use 'PERFECT_ENTRY' mode for the Alpha Strike
            asset = self.factory.generate_gift({"name": biz_name, "niche": niche}, mode="PERFECT_ENTRY")
            
            # PHASE 2: Provision a REAL Vapi Agent for this lead
            print(f"  > Provisioning Demo Agent for: {biz_name}...")
            agent = self.provisioner.create_alpha_agent(biz_name, niche)
            
            results.append({
                "lead": lead,
                "asset": asset,
                "agent_id": agent.get("id"),
                "status": "GENERATED"
            })
            
        output_file = self.output_dir / f"{batch_name}.json"
        with open(output_file, "w", encoding="utf-8") as f:
            json.dump(results, f, indent=4)
        
        print(f"✅ Batch {batch_name} complete! Results saved to {output_file}")

if __name__ == "__main__":
    generator = BatchGiftGenerator()
    csv_file = GENESIS_ROOT / "data" / "LEADS" / "TRADIE LEADS AUSTRALIA" / "ZOHO_SIMPLE_IMPORT.csv"
    
    # Run a small pilot batch of 5 for verification first
    top_5 = generator.extract_top_leads(str(csv_file), limit=5)
    asyncio.run(generator.run_batch(top_5, "alpha_strike_pilot_v1"))
