import pandas as pd
import os
import sys
from typing import List, Dict, Any

# Add tools to path
sys.path.append(os.path.dirname(__file__))
from ghl_mcp_bridge import GHLMCPBridge

class GHLRoundTripSync:
    def __init__(self, api_key: str, location_id: str):
        self.api_key = api_key
        self.location_id = location_id
        # Initialize bridge to standard GHL MCP server location
        self.bridge = GHLMCPBridge(r"E:\genesis-system\mcp-servers\ghl", env={
            "GHL_API_KEY": self.api_key,
            "GHL_LOCATION_ID": self.location_id
        })
        
    def import_segmented_leads(self, csv_file: str, tag: str):
        """
        Imports leads from a CSV file into GHL and tags them.
        """
        print(f"🔄 [Sync] Importing leads from {csv_file} with tag '{tag}'...")
        df = pd.read_csv(csv_file).fillna('')
        
        # Batching for API efficiency
        batch_size = 5
        for i in range(0, min(len(df), 5), batch_size): # Limit to 5 for safety during setup
            batch = df.iloc[i:i+batch_size]
            for _, row in batch.iterrows():
                contact_data = {
                    "firstName": row.get('Last Name', ''),  # Treating entity name as first name for visibility
                    "companyName": row.get('Company', ''),
                    "email": row.get('Email', ''),
                    "phone": row.get('Phone', ''),
                    "address1": row.get('Street', ''),
                    "city": row.get('City', ''),
                    "state": row.get('State', ''),
                    "postalCode": row.get('Zip Code', ''),
                    "country": row.get('Country', ''),
                    "locationId": self.location_id,
                    "tags": [tag, "Genesis-Prong-1"]
                }
                
                # Check for existing email/phone to prevent duplicates
                if not contact_data['email'] and not contact_data['phone']:
                    continue
                
                identifier = contact_data['email'] or contact_data['phone']
                print(f"  - Creating contact: {identifier}")
                result = self.bridge.call_tool("create_contact", contact_data)
                print(f"    Result: {result.get('result', {}).get('status', 'unknown')}")

        print(f"✅ [Sync] Import batch complete.")

if __name__ == "__main__":
    # Test with High-Value Tradies
    # Load from env or use provided defaults (ensure these are set in your environment)
    GHL_API_KEY = os.getenv("GHL_API_KEY", "pit-91962a1c-ae7f-4ef4-8335-2d61f27faf22")
    LOCATION_ID = os.getenv("GHL_LOCATION_ID", "73q7bKDm2d6hsCtHuz1m")
    
    sync = GHLRoundTripSync(GHL_API_KEY, LOCATION_ID)
    tradie_csv = r"e:\genesis-system\data\LEADS\SEGMENTED\tradies_high_value_priority.csv"
    
    if os.path.exists(tradie_csv):
        sync.import_segmented_leads(tradie_csv, "High-Value-Tradie-AU")
    else:
        print(f"❌ Lead file not found: {tradie_csv}")
