#!/usr/bin/env python3
"""
GHL Direct Execution - Create knowledge graph entities via Gemini
Using new google.genai package
"""
import os
import json
import time
from datetime import datetime
from pathlib import Path

# Load API key
def get_api_key():
    key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
    if not key:
        env_path = Path("/mnt/e/genesis-system/.env")
        if env_path.exists():
            with open(env_path) as f:
                for line in f:
                    if "GEMINI_API_KEY=" in line or "GOOGLE_API_KEY=" in line:
                        key = line.split("=", 1)[1].strip().strip('"')
                        break
    return key

api_key = get_api_key()
if not api_key:
    print("ERROR: No Gemini API key found")
    exit(1)

# Use new google.genai package
from google import genai
from google.genai import types

client = genai.Client(api_key=api_key)

OUTPUT_DIR = Path("/mnt/e/genesis-system/KNOWLEDGE_GRAPH/entities/ghl")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

# Read existing MCP README for context
mcp_readme = Path("/mnt/e/genesis-system/mcp-servers/ghl/README.md").read_text()

stories = [
    {
        "id": "GHL-001",
        "title": "GHL API Endpoints Knowledge Graph",
        "prompt": f"""Create a comprehensive JSON knowledge graph entity for GHL (GoHighLevel) API endpoints.

Based on this MCP server documentation:
{mcp_readme[:15000]}

Create a JSON file with ALL API endpoint details including:
- Endpoint path
- HTTP method
- Required parameters with types
- Optional parameters
- Response schema
- Rate limits
- Example usage

Output ONLY valid JSON, no markdown fences or explanation.
Structure: {{"entity_type": "api_endpoints", "base_url": "https://services.leadconnectorhq.com", "endpoints": [...]}}
""",
        "output": "ghl_api_endpoints.json"
    },
    {
        "id": "GHL-002",
        "title": "GHL Agent Studio Entities",
        "prompt": """Create a comprehensive JSON knowledge graph entity for GHL Agent Studio.

Include:
- All node types (LLM, MCP, API, Knowledge Base, Web Search, Content Generation)
- Deployment lifecycle (Draft, Staging, Production)
- Agent types (Voice AI Inbound, Voice AI Outbound, Conversation AI, Reviews AI, Funnel AI, Content AI)
- Integration patterns
- Configuration options
- Best practices

Output ONLY valid JSON, no markdown fences or explanation.
Structure: {"entity_type": "agent_studio", "node_types": [...], "agent_types": [...], "deployment_lifecycle": [...], "best_practices": [...]}
""",
        "output": "ghl_agent_studio.json"
    },
    {
        "id": "GHL-003",
        "title": "GHL Marketplace Apps",
        "prompt": """Create a comprehensive JSON knowledge graph entity for GHL Marketplace apps.

Include Final Straw apps and strategic integrations:
- AVA Voice AI (24/7 Receptionist)
- Voizer.ai (Outbound Cold Calling)
- Extendly AI Receptionist
- AI Booking ChatBOT
- Marketing Agency AI Agent
- HL Snaps snapshots
- Other voice AI integrations

For each app include:
- Name, description, category
- Pricing (monthly/one-time)
- Key features
- Integration requirements
- Use cases
- ROI potential

Output ONLY valid JSON, no markdown fences or explanation.
Structure: {"entity_type": "marketplace_apps", "total_apps": 1500, "strategic_apps": [...]}
""",
        "output": "ghl_marketplace_apps.json"
    },
    {
        "id": "GHL-004",
        "title": "GHL Pricing Intelligence",
        "prompt": """Create a comprehensive JSON knowledge graph entity for GHL pricing.

Include ALL pricing tiers and costs:
- Starter Plan ($97/mo) - core CRM, marketing, funnels
- Unlimited Plan ($297/mo) - unlimited subaccounts
- SaaS Pro Plan ($497/mo) - white-label, billing tools
- Unlimited AI Plan ($97/mo per sub-account) - Agent Studio access
- Voice AI per-minute costs
- SMS costs per segment (US vs international)
- Email sending costs
- Phone number costs (US vs AU)
- Agent Studio pay-per-use rates

Also include:
- Feature comparison between tiers
- Cost optimization strategies
- Australian market premium positioning ($497-697/mo for Voice AI)

Output ONLY valid JSON, no markdown fences or explanation.
Structure: {"entity_type": "pricing_intelligence", "tiers": [...], "usage_costs": {...}, "optimization_strategies": [...], "australian_premium": {...}}
""",
        "output": "ghl_pricing_intelligence.json"
    },
    {
        "id": "GHL-005",
        "title": "GHL Custom Fields Catalog",
        "prompt": """Create a comprehensive JSON knowledge graph entity for GHL custom fields.

Include:
- All standard contact fields (firstName, lastName, email, phone, etc.)
- Common custom field configurations by niche:
  - Tradies (job_type, property_access, emergency_flag, service_area)
  - Real estate (property_value, bedrooms, property_type, buyer_seller)
  - Medical (patient_id, insurance, provider, appointment_type)
  - E-commerce (order_history, preferences, lifetime_value)
- Field types (text, dropdown, date, checkbox, number, textarea)
- Validation rules
- Import/export mapping patterns

Output ONLY valid JSON, no markdown fences or explanation.
Structure: {"entity_type": "custom_fields_catalog", "standard_fields": [...], "niche_fields": {...}, "field_types": [...], "validation_rules": [...]}
""",
        "output": "ghl_custom_fields.json"
    }
]

results = []
for story in stories:
    print(f"\n{'='*60}")
    print(f"Executing: {story['id']} - {story['title']}")
    print(f"{'='*60}")

    try:
        start = time.time()

        response = client.models.generate_content(
            model="gemini-2.0-flash",
            contents=story['prompt']
        )

        elapsed = time.time() - start

        # Extract JSON from response
        text = response.text.strip()
        if text.startswith("```"):
            text = text.split("```")[1]
            if text.startswith("json"):
                text = text[4:]
        text = text.strip()

        # Validate JSON
        data = json.loads(text)

        # Write to file
        output_path = OUTPUT_DIR / story['output']
        with open(output_path, 'w') as f:
            json.dump(data, f, indent=2)

        print(f"✅ Success in {elapsed:.1f}s - Wrote {output_path}")
        results.append({"id": story['id'], "status": "success", "file": str(output_path), "duration": elapsed})

    except json.JSONDecodeError as e:
        print(f"❌ JSON Parse Error: {e}")
        # Save raw response for debugging
        debug_path = OUTPUT_DIR / f"{story['output']}.raw.txt"
        with open(debug_path, 'w') as f:
            f.write(text if 'text' in dir() else "No response")
        results.append({"id": story['id'], "status": "json_error", "error": str(e)})

    except Exception as e:
        print(f"❌ Failed: {e}")
        results.append({"id": story['id'], "status": "failed", "error": str(e)})

    time.sleep(2)  # Rate limit respect

# Summary
print(f"\n{'='*60}")
print("EXECUTION SUMMARY")
print(f"{'='*60}")
success = sum(1 for r in results if r['status'] == 'success')
print(f"Success: {success}/{len(results)}")

# Write report
report_path = Path("/mnt/e/genesis-system/loop/GHL_DIRECT_EXECUTION_REPORT.md")
with open(report_path, 'w') as f:
    f.write(f"# GHL Direct Execution Report\n")
    f.write(f"**Generated:** {datetime.now().isoformat()}\n\n")
    f.write(f"## Summary\n")
    f.write(f"- Stories: {len(results)}\n")
    f.write(f"- Successful: {success}\n")
    f.write(f"- Failed: {len(results) - success}\n\n")
    f.write(f"## Results\n")
    for r in results:
        status = "✅" if r['status'] == 'success' else "❌"
        f.write(f"### {status} {r['id']}\n")
        f.write(f"- Status: {r['status']}\n")
        if 'file' in r:
            f.write(f"- File: {r['file']}\n")
        if 'duration' in r:
            f.write(f"- Duration: {r['duration']:.1f}s\n")
        if 'error' in r:
            f.write(f"- Error: {r['error']}\n")
        f.write("\n")

print(f"\nReport: {report_path}")
