import os
import httpx
import json

TELNYX_API_KEY = os.environ.get("TELNYX_API_KEY", "")

# Load from secrets if not in environment
if not TELNYX_API_KEY:
    try:
        from pathlib import Path
        BASE_DIR = Path(__file__).parent.parent
        with open(BASE_DIR / "config" / "secrets.env", "r") as f:
            for line in f:
                if line.startswith("TELNYX_API_KEY="):
                    TELNYX_API_KEY = line.split("=", 1)[1].strip().strip('"\'')
    except Exception:
        pass

async def spawn_telnyx_assistant(business_name: str, core_offer: str, brand_archetype: str) -> str:
    """
    Programmatically creates a new Telnyx AI Assistant instance dynamically configured
    for the specific generated business using the extracted data.
    
    Returns the new assistant_id.
    """
    if not TELNYX_API_KEY:
        print("[Telnyx JIT] Missing TELNYX_API_KEY. Returning dummy assistant_id.")
        return "assistant-dummy-555-444"
        
    system_prompt = f"""
    You are the AI Voice Receptionist for {business_name}. 
    Your primary goal is to book appointments and capture leads for {core_offer}.
    Tone/Brand Archetype: {brand_archetype}.
    
    Keep responses concise and conversational. If asked about pricing, be vague and offer a free quote.
    """
    
    payload = {
        "name": f"AI_Agent_{business_name.replace(' ', '_')}",
        "language": "en",
        "instructions": system_prompt,
        "voice": "eleven_turbo_v2_5", # Standard fast voice
        "model": "Qwen/Qwen3-235B-A22B"
    }
    
    headers = {
        "Authorization": f"Bearer {TELNYX_API_KEY}",
        "Content-Type": "application/json",
        "Accept": "application/json"
    }
    
    try:
        async with httpx.AsyncClient() as client:
            print(f"[{business_name}] Provisioning robust isolated Telnyx Assistant...")
            # Note: The exact Telnyx Assistants API endpoint may vary depending on their latest documentation,
            # this represents the logical integration point for programmatic creation.
            # E.g. https://api.telnyx.com/v2/ai/assistants
            response = await client.post(
                "https://api.telnyx.com/v2/ai/assistants",
                headers=headers,
                json=payload
            )
            
            if response.status_code in (200, 201):
                data = response.json()
                assistant_id = data.get("data", {}).get("id") or data.get("id")
                print(f"[{business_name}] Telnyx Assistant provisioned: {assistant_id}")
                return assistant_id
            else:
                print(f"[{business_name}] Telnyx Assistant creation failed: {response.text}")
                return "assistant-error-creation-failed"
                
    except Exception as e:
        print(f"[{business_name}] Telnyx Assistant JIT completely failed: {e}")
        return "assistant-network-failure"
