#!/usr/bin/env python3
"""
ReceptionistAI - Client Onboarding Orchestrator
================================================
Master script that orchestrates the full client onboarding flow.

Usage:
    python onboarding_orchestrator.py --onboard "Business Name" --email "client@email.com" --plan starter
    python onboarding_orchestrator.py --status "client_id"
"""

import os
import sys
import json
import argparse
from datetime import datetime
from pathlib import Path

# Add paths
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from RECEPTIONISTAI.scripts.ghl_template_setup import GHLTemplateManager
from RECEPTIONISTAI.scripts.telnyx_provisioner import TelnyxProvisioner
from RECEPTIONISTAI.scripts.vapi_client_template import VAPIClientTemplate


class OnboardingOrchestrator:
    """Orchestrates full client onboarding for ReceptionistAI."""

    def __init__(self):
        self.ghl = GHLTemplateManager()
        self.telnyx = TelnyxProvisioner()
        self.vapi = VAPIClientTemplate()

        # Onboarding state file
        self.state_dir = Path(__file__).parent.parent / "onboarding_state"
        self.state_dir.mkdir(exist_ok=True)

    def generate_client_id(self, business_name: str) -> str:
        """Generate unique client ID."""
        import hashlib
        timestamp = datetime.utcnow().strftime("%Y%m%d%H%M%S")
        name_hash = hashlib.md5(business_name.encode()).hexdigest()[:6]
        return f"RAI-{timestamp}-{name_hash}"

    def save_state(self, client_id: str, state: dict):
        """Save onboarding state to file."""
        state_file = self.state_dir / f"{client_id}.json"
        with open(state_file, "w") as f:
            json.dump(state, f, indent=2)

    def load_state(self, client_id: str) -> dict:
        """Load onboarding state from file."""
        state_file = self.state_dir / f"{client_id}.json"
        if state_file.exists():
            with open(state_file) as f:
                return json.load(f)
        return None

    def onboard_client(self, client_info: dict) -> dict:
        """
        Full onboarding flow:
        1. Create GHL contact
        2. Create VAPI agent
        3. Provision Telnyx number
        4. Connect number to agent
        5. Send welcome email
        """

        business_name = client_info.get("business_name", "New Client")
        client_id = self.generate_client_id(business_name)

        print(f"\n{'='*60}")
        print(f"🚀 ONBOARDING: {business_name}")
        print(f"   Client ID: {client_id}")
        print(f"{'='*60}\n")

        state = {
            "client_id": client_id,
            "business_name": business_name,
            "client_info": client_info,
            "started_at": datetime.utcnow().isoformat(),
            "status": "in_progress",
            "steps": {}
        }

        # Step 1: Create GHL Contact
        print("📇 Step 1: Creating GHL Contact...")
        try:
            ghl_result = self.ghl.clone_for_client(business_name, {
                "name": client_info.get("contact_name", business_name),
                "email": client_info.get("email"),
                "phone": client_info.get("phone"),
                "business_type": client_info.get("business_type", "general"),
                "plan": client_info.get("plan", "Starter")
            })
            state["steps"]["ghl_contact"] = {
                "status": "success" if "error" not in ghl_result else "failed",
                "result": ghl_result,
                "completed_at": datetime.utcnow().isoformat()
            }
            print(f"   ✓ GHL Contact created")
        except Exception as e:
            state["steps"]["ghl_contact"] = {"status": "failed", "error": str(e)}
            print(f"   ✗ GHL Contact failed: {e}")

        # Step 2: Create VAPI Agent
        print("🤖 Step 2: Creating VAPI Agent...")
        try:
            agent_info = {
                "business_name": business_name,
                "industry": client_info.get("business_type", "generic"),
                "ai_name": client_info.get("ai_name", "Sarah"),
                "service_type": client_info.get("service_type", client_info.get("business_type", "services")),
                "hours": client_info.get("hours", "Monday-Friday 8am-5pm"),
                "voice": client_info.get("voice", "female_au")
            }
            vapi_result = self.vapi.create_client_agent(agent_info)
            state["steps"]["vapi_agent"] = {
                "status": "success" if "id" in vapi_result else "failed",
                "agent_id": vapi_result.get("id"),
                "result": vapi_result,
                "completed_at": datetime.utcnow().isoformat()
            }
            if "id" in vapi_result:
                print(f"   ✓ VAPI Agent created: {vapi_result['id']}")
            else:
                print(f"   ✗ VAPI Agent failed")
        except Exception as e:
            state["steps"]["vapi_agent"] = {"status": "failed", "error": str(e)}
            print(f"   ✗ VAPI Agent failed: {e}")

        # Step 3: Search for Telnyx Number (manual provisioning recommended)
        print("📞 Step 3: Searching for Phone Numbers...")
        try:
            telnyx_search = self.telnyx.search_available_numbers("AU", 5)
            state["steps"]["telnyx_search"] = {
                "status": "success" if "data" in telnyx_search else "failed",
                "available_numbers": [n.get("phone_number") for n in telnyx_search.get("data", [])],
                "note": "Manual purchase required via Telnyx dashboard",
                "completed_at": datetime.utcnow().isoformat()
            }
            if "data" in telnyx_search and telnyx_search["data"]:
                print(f"   ✓ Found {len(telnyx_search['data'])} available numbers")
                print(f"   ⚠ Manual purchase required in Telnyx dashboard")
            else:
                print(f"   ⚠ No numbers found or API issue")
        except Exception as e:
            state["steps"]["telnyx_search"] = {"status": "failed", "error": str(e)}
            print(f"   ✗ Telnyx search failed: {e}")

        # Step 4: Generate credentials and save
        print("🔐 Step 4: Generating Credentials...")
        credentials = {
            "client_id": client_id,
            "business_name": business_name,
            "vapi_agent_id": state["steps"].get("vapi_agent", {}).get("agent_id"),
            "phone_number": "PENDING - Manual provisioning required",
            "dashboard_url": "https://receptionistai.au/dashboard",
            "support_email": "support@receptionistai.au"
        }
        state["credentials"] = credentials
        print(f"   ✓ Credentials generated")

        # Determine final status
        steps_status = [s.get("status") for s in state["steps"].values()]
        if all(s == "success" for s in steps_status):
            state["status"] = "completed"
        elif any(s == "success" for s in steps_status):
            state["status"] = "partial"
        else:
            state["status"] = "failed"

        state["completed_at"] = datetime.utcnow().isoformat()

        # Save state
        self.save_state(client_id, state)

        print(f"\n{'='*60}")
        print(f"📋 ONBOARDING STATUS: {state['status'].upper()}")
        print(f"   Client ID: {client_id}")
        print(f"   State file: {self.state_dir / f'{client_id}.json'}")
        print(f"{'='*60}\n")

        # Print next steps
        print("📝 NEXT STEPS:")
        if state["steps"].get("telnyx_search", {}).get("status") == "success":
            numbers = state["steps"]["telnyx_search"].get("available_numbers", [])
            if numbers:
                print(f"   1. Purchase phone number in Telnyx: {numbers[0]}")
        print(f"   2. Connect number to VAPI agent: {credentials.get('vapi_agent_id')}")
        print(f"   3. Send welcome email to: {client_info.get('email')}")
        print(f"   4. Schedule 7-day check-in call")

        return state

    def get_status(self, client_id: str) -> dict:
        """Get onboarding status for a client."""
        state = self.load_state(client_id)
        if not state:
            return {"error": f"Client {client_id} not found"}
        return state


def main():
    parser = argparse.ArgumentParser(description="ReceptionistAI Onboarding Orchestrator")
    parser.add_argument("--onboard", type=str, help="Business name to onboard")
    parser.add_argument("--email", type=str, help="Client email")
    parser.add_argument("--phone", type=str, help="Client phone")
    parser.add_argument("--plan", type=str, default="starter", help="Plan (starter/professional/enterprise)")
    parser.add_argument("--type", type=str, default="generic", help="Business type")
    parser.add_argument("--status", type=str, help="Get status for client ID")
    parser.add_argument("--list", action="store_true", help="List all onboarding states")

    args = parser.parse_args()

    orchestrator = OnboardingOrchestrator()

    if args.onboard:
        client_info = {
            "business_name": args.onboard,
            "email": args.email,
            "phone": args.phone,
            "plan": args.plan,
            "business_type": args.type
        }
        orchestrator.onboard_client(client_info)

    elif args.status:
        state = orchestrator.get_status(args.status)
        print(json.dumps(state, indent=2))

    elif args.list:
        state_dir = Path(__file__).parent.parent / "onboarding_state"
        if state_dir.exists():
            for f in state_dir.glob("*.json"):
                with open(f) as file:
                    state = json.load(file)
                print(f"{state.get('client_id')} | {state.get('business_name')} | {state.get('status')}")
        else:
            print("No onboarding states found")

    else:
        parser.print_help()


if __name__ == "__main__":
    main()
