#!/usr/bin/env python3
"""QA Mystery Shopper - runs automated test calls against Leah/Sam"""

import json, os, sys, time, urllib.request

VAPI_KEY = open(os.path.expanduser("~/.openclaw/secrets/vapi-api-key.txt")).read().strip()
QA_ASSISTANT_ID = "03b70307-7178-40df-b4ec-f2a10d5fa523"

# Hardcoded phone number IDs (from Vapi)
PHONE_IDS = {
    "+16473609178": "1422e5da-60eb-4ae4-9ad5-16bd43f0d348",  # Harvey
    "+16477992731": "92fcdba1-348c-4644-a1e6-d5f4c421586b",  # Leah staging
    "+16477993198": "ad0703df-8179-4933-925f-17201b47fad5",  # Sam staging
}

def vapi_curl(method, path, data=None):
    """Use curl subprocess to avoid urllib SSL/header issues with Vapi"""
    import subprocess
    url = f"https://api.vapi.ai{path}"
    cmd = ["curl", "-s", "-X", method, url, "-H", f"Authorization: Bearer {VAPI_KEY}"]
    if data:
        cmd += ["-H", "Content-Type: application/json", "-d", json.dumps(data)]
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
    if result.returncode != 0:
        raise RuntimeError(f"curl failed: {result.stderr}")
    return json.loads(result.stdout)

def run_scenario(scenario, index):
    print(f"\n{'='*60}")
    print(f"TEST {index+1}: {scenario['name']}")
    print(f"Calling {scenario['target']} from {scenario['from']}")
    print(f"{'='*60}")
    
    # Create outbound call with scenario-specific overrides
    call_data = {
        "assistantId": QA_ASSISTANT_ID,
        "assistantOverrides": {
            "model": {
                "model": "gpt-4o",
                "provider": "openai",
                "temperature": 0.7,
                "messages": [{"role": "system", "content": scenario["prompt"]}]
            },
            "firstMessage": scenario["firstMessage"]
        },
        "phoneNumberId": None,  # will be set below
        "customer": {
            "number": scenario["target"]
        }
    }
    
    from_id = PHONE_IDS.get(scenario["from"])
    if not from_id:
        print(f"ERROR: No phone ID mapped for {scenario['from']}")
        return None
    
    call_data["phoneNumberId"] = from_id
    
    try:
        result = vapi_curl("POST", "/call/phone", call_data)
        call_id = result.get("id", "?")
        print(f"Call initiated: {call_id}")
        print(f"Status: {result.get('status', '?')}")
        return call_id
    except Exception as e:
        print(f"ERROR creating call: {e}")
        return None

def get_call_transcript(call_id, max_wait=180):
    """Poll until call ends and return transcript"""
    print(f"Waiting for call {call_id} to complete...")
    start = time.time()
    while time.time() - start < max_wait:
        try:
            call = vapi_curl("GET", f"/call/{call_id}")
            status = call.get("status", "?")
            if status == "ended":
                transcript = call.get("transcript", "No transcript available")
                duration = call.get("duration", call.get("endedReason", "?"))
                print(f"Call ended. Duration: {duration}s. Reason: {call.get('endedReason','?')}")
                return {
                    "transcript": transcript,
                    "duration": duration,
                    "endedReason": call.get("endedReason", "?"),
                    "messages": call.get("messages", []),
                    "analysis": call.get("analysis", {})
                }
            elif status in ("queued", "ringing", "in-progress"):
                sys.stdout.write(".")
                sys.stdout.flush()
                time.sleep(5)
            else:
                print(f"Unexpected status: {status}")
                time.sleep(5)
        except Exception as e:
            print(f"Error polling: {e}")
            time.sleep(5)
    
    print("Timeout waiting for call to complete")
    return None

def main():
    with open("/tmp/qa-scenarios.json") as f:
        scenarios = json.load(f)
    
    # Parse args
    if len(sys.argv) > 1:
        # Run specific test number(s)
        indices = [int(x)-1 for x in sys.argv[1:]]
    else:
        indices = range(len(scenarios))
    
    results = []
    for i in indices:
        if i >= len(scenarios):
            print(f"Skipping test {i+1}: out of range")
            continue
        
        call_id = run_scenario(scenarios[i], i)
        if call_id:
            # Wait between calls
            transcript_data = get_call_transcript(call_id)
            results.append({
                "test": scenarios[i]["name"],
                "call_id": call_id,
                "data": transcript_data
            })
            
            if transcript_data:
                print(f"\n--- TRANSCRIPT ---")
                print(transcript_data.get("transcript", "N/A")[:2000])
                print(f"--- END ---\n")
            
            # Wait 10s between calls to avoid overwhelming
            if i < max(indices):
                print("Waiting 10s before next call...")
                time.sleep(10)
    
    # Save results
    output_file = os.path.expanduser("~/.openclaw/workspace/leah/qa-results.json")
    with open(output_file, "w") as f:
        json.dump(results, f, indent=2, default=str)
    print(f"\nResults saved to {output_file}")
    print(f"Total tests run: {len(results)}")

if __name__ == "__main__":
    main()
