#!/usr/bin/env python3
"""
ReceptionistAI - GHL Sub-Account Template Setup
================================================
Creates and configures the ReceptionistAI template sub-account in GHL.

Usage:
    python ghl_template_setup.py --create-template
    python ghl_template_setup.py --clone-for-client "Business Name"
"""

import os
import sys
import json
import requests
import argparse
from datetime import datetime
from pathlib import Path

# Add genesis path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

class GHLTemplateManager:
    """Manages GHL sub-account templates for ReceptionistAI."""

    def __init__(self):
        self.agency_key = os.getenv("GHL_AGENCY_KEY", "pit-b9be7195-e808-4f95-a984-34f9dcab51c4")
        self.location_id = os.getenv("GHL_LOCATION_ID", "73q7bKDm2d6hsCtHuz1m")
        self.base_url = "https://services.leadconnectorhq.com"
        self.headers = {
            "Authorization": f"Bearer {self.agency_key}",
            "Content-Type": "application/json",
            "Version": "2021-07-28"
        }

        # ReceptionistAI branding
        self.brand = {
            "name": "ReceptionistAI",
            "primary_color": "#6366F1",  # Purple
            "secondary_color": "#0D9488",  # Teal
            "accent_color": "#EC4899",  # Pink
            "domain": "receptionistai.au"
        }

        # Pipeline stages
        self.pipelines = {
            "sales": {
                "name": "Sales Pipeline",
                "stages": [
                    {"name": "Lead", "order": 1},
                    {"name": "Demo Requested", "order": 2},
                    {"name": "Demo Completed", "order": 3},
                    {"name": "Proposal Sent", "order": 4},
                    {"name": "Closing Call", "order": 5},
                    {"name": "Won", "order": 6},
                    {"name": "Lost", "order": 7}
                ]
            },
            "onboarding": {
                "name": "Client Onboarding",
                "stages": [
                    {"name": "Payment Received", "order": 1},
                    {"name": "Info Gathering", "order": 2},
                    {"name": "Agent Setup", "order": 3},
                    {"name": "Testing", "order": 4},
                    {"name": "Live", "order": 5}
                ]
            }
        }

    def _make_request(self, method: str, endpoint: str, data: dict = None) -> dict:
        """Make API request to GHL."""
        url = f"{self.base_url}{endpoint}"
        try:
            if method == "GET":
                response = requests.get(url, headers=self.headers, timeout=30)
            elif method == "POST":
                response = requests.post(url, headers=self.headers, json=data, timeout=30)
            elif method == "PUT":
                response = requests.put(url, headers=self.headers, json=data, timeout=30)
            else:
                return {"error": f"Unsupported method: {method}"}

            if response.status_code in [200, 201]:
                return response.json() if response.text else {"status": "success"}
            else:
                return {"error": response.text, "status_code": response.status_code}
        except Exception as e:
            return {"error": str(e)}

    def get_location_info(self) -> dict:
        """Get current location info."""
        return self._make_request("GET", f"/locations/{self.location_id}")

    def create_contact(self, contact_data: dict) -> dict:
        """Create a new contact in GHL."""
        payload = {
            "locationId": self.location_id,
            **contact_data
        }
        return self._make_request("POST", "/contacts/", payload)

    def create_pipeline(self, pipeline_config: dict) -> dict:
        """Create a pipeline with stages."""
        payload = {
            "locationId": self.location_id,
            "name": pipeline_config["name"],
            "stages": pipeline_config["stages"]
        }
        return self._make_request("POST", "/opportunities/pipelines", payload)

    def setup_calendar(self) -> dict:
        """Configure appointment calendar."""
        calendar_config = {
            "locationId": self.location_id,
            "name": "ReceptionistAI Demo Calls",
            "description": "15-minute demo calls with potential clients",
            "slotDuration": 15,
            "slotBuffer": 5,
            "availableHours": {
                "monday": {"start": "09:00", "end": "17:00"},
                "tuesday": {"start": "09:00", "end": "17:00"},
                "wednesday": {"start": "09:00", "end": "17:00"},
                "thursday": {"start": "09:00", "end": "17:00"},
                "friday": {"start": "09:00", "end": "17:00"}
            }
        }
        return self._make_request("POST", "/calendars/", calendar_config)

    def create_custom_fields(self) -> list:
        """Create custom fields for ReceptionistAI."""
        fields = [
            {"name": "Business Type", "fieldKey": "business_type", "dataType": "TEXT"},
            {"name": "Missed Calls/Week", "fieldKey": "missed_calls_week", "dataType": "NUMBER"},
            {"name": "Avg Job Value", "fieldKey": "avg_job_value", "dataType": "NUMBER"},
            {"name": "Monthly Loss", "fieldKey": "monthly_loss", "dataType": "NUMBER"},
            {"name": "VAPI Agent ID", "fieldKey": "vapi_agent_id", "dataType": "TEXT"},
            {"name": "Telnyx Number", "fieldKey": "telnyx_number", "dataType": "TEXT"},
            {"name": "Subscription Plan", "fieldKey": "subscription_plan", "dataType": "TEXT"},
            {"name": "Onboarding Status", "fieldKey": "onboarding_status", "dataType": "TEXT"}
        ]

        results = []
        for field in fields:
            field["locationId"] = self.location_id
            result = self._make_request("POST", "/locations/custom-fields", field)
            results.append(result)
        return results

    def setup_template(self) -> dict:
        """Full template setup."""
        print("🚀 Setting up ReceptionistAI GHL Template...")

        results = {
            "timestamp": datetime.utcnow().isoformat(),
            "location_info": None,
            "pipelines": [],
            "calendar": None,
            "custom_fields": []
        }

        # Get location info
        print("📍 Fetching location info...")
        results["location_info"] = self.get_location_info()

        # Create pipelines
        print("📊 Creating pipelines...")
        for key, config in self.pipelines.items():
            result = self.create_pipeline(config)
            results["pipelines"].append({key: result})
            print(f"   - {config['name']}: {'✓' if 'error' not in result else '✗'}")

        # Setup calendar
        print("📅 Setting up calendar...")
        results["calendar"] = self.setup_calendar()

        # Create custom fields
        print("🏷️ Creating custom fields...")
        results["custom_fields"] = self.create_custom_fields()

        # Save results
        output_path = Path(__file__).parent / "ghl_template_setup_results.json"
        with open(output_path, "w") as f:
            json.dump(results, f, indent=2)

        print(f"\n✅ Template setup complete! Results saved to {output_path}")
        return results

    def clone_for_client(self, business_name: str, contact_info: dict) -> dict:
        """Clone template for a new client."""
        print(f"🔄 Creating sub-account for: {business_name}")

        # Create contact first
        contact_data = {
            "name": contact_info.get("name", business_name),
            "email": contact_info.get("email"),
            "phone": contact_info.get("phone"),
            "companyName": business_name,
            "customFields": [
                {"key": "business_type", "value": contact_info.get("business_type", "")},
                {"key": "subscription_plan", "value": contact_info.get("plan", "Starter")},
                {"key": "onboarding_status", "value": "Payment Received"}
            ]
        }

        contact_result = self.create_contact(contact_data)

        return {
            "business_name": business_name,
            "contact": contact_result,
            "next_steps": [
                "1. Create VAPI agent from template",
                "2. Provision Telnyx number",
                "3. Connect number to agent",
                "4. Send credentials email"
            ]
        }


def main():
    parser = argparse.ArgumentParser(description="GHL Template Manager for ReceptionistAI")
    parser.add_argument("--create-template", action="store_true", help="Setup the template sub-account")
    parser.add_argument("--clone-for-client", type=str, help="Clone template for a new client")
    parser.add_argument("--get-info", action="store_true", help="Get current location info")

    args = parser.parse_args()

    manager = GHLTemplateManager()

    if args.create_template:
        manager.setup_template()
    elif args.clone_for_client:
        result = manager.clone_for_client(args.clone_for_client, {})
        print(json.dumps(result, indent=2))
    elif args.get_info:
        info = manager.get_location_info()
        print(json.dumps(info, indent=2))
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
