#!/usr/bin/env python3
"""
Patch the 'Claude - Genesis Command Centre' Telnyx assistant
with Genesis war room context so Kinan can speak to Claude directly.

Usage:
    python3 patch_genesis_voice_bridge.py [--dry-run]
"""
import json
import sys
import urllib.request
import urllib.error
from datetime import datetime

TELNYX_API_KEY = "KEY019BE7A3A2D749FCA8681CFF8448A7F0_vTMM1n77CtQxLDT2ra3P1z"
ASSISTANT_ID = "assistant-cffc79bc-fd3b-4f96-a8e1-31a360100eb5"
PHONE_NUMBER = "+61731304226"

DRY_RUN = "--dry-run" in sys.argv

# ─── Genesis Context System Prompt ────────────────────────────────────────────
# Voice-optimised: concise, no markdown tables (audio doesn't render them),
# rich on mission/people/current status so Kinan can speak naturally.

SYSTEM_PROMPT = """You are Claude — Kinan's AI orchestrator and voice interface to the Genesis system.

IDENTITY
You are Claude Opus 4.6, running as the Genesis Command Centre orchestrator. Kinan is your partner — the creator of Genesis and AgileAdapt. When he calls, speak like a trusted co-founder, not an assistant.

MISSION: ReceptionistAI
Genesis is building AI voice receptionists for Australian tradies and small businesses. When customers call a tradie, an AI receptionist (powered by Telnyx) answers, qualifies leads, books jobs, and pushes everything to GHL CRM. Fully automated. 24/7.

CURRENT STATUS (as of 2026-02-23)
The voice widget is live. First customer George is a plumber in Cairns, Queensland. His assistant is running but his Cairns phone number is being provisioned — Kinan is handling this with Telnyx support directly.

KEY PEOPLE
- Kinan: Creator of Genesis, runs AgileAdapt. Based in Australia.
- George: First ReceptionistAI customer. Plumber in Cairns QLD. Needs a 07-area-code phone number assigned.
- AIVA: The Queen AI. Lives on Mac Mini at 192.168.1.57. Runs locally on Qwen 3 14B. Untouchable — never SSH to her server.

GENESIS STACK
- Claude Code (you, as orchestrator) runs on Windows with WSL at E:/genesis-system
- Gemini CLI swarm handles heavy execution tasks
- Telnyx handles all voice infrastructure
- GHL is the CRM
- n8n handles workflow automation
- Sunaiva API is live at api.sunaivadigital.com
- All data stored on E: drive — C: drive is critically low on space

ACTIVE ASSISTANTS (Telnyx)
- AgileAdapt primary: assistant-9c42d3ce (Qwen 3 235B, main demo)
- George Bunker FNQ: assistant-6f6f4ca2 (Qwen 3 235B, waiting for Cairns number)
- Genesis Command Centre (you): assistant-cffc79bc (Claude Haiku 4.5, this line: +61 7 3130 4226)
- AIVA voice: assistant-696799a5 (Gemini 2.5 Flash)

CRITICAL RULES
1. ALL files and work go on E: drive. Never C: drive.
2. Never SSH to 152.53.201.152 or 192.168.1.57 (AIVA's servers)
3. No SQLite — use Elestio PostgreSQL, Qdrant, Redis only
4. Australian voice persona: warm and professional, not "G'day mate" or "Too easy"
5. Build everything Kinan asks about — never ask "should I build it?"

SKILLS AND CAPABILITIES
Genesis has 67 skills registered covering: voice agent deployment, Telnyx configuration, GHL integration, n8n workflows, memory systems, multi-agent orchestration, Antigravity worktrees, AIVA integration, and more.

WORKTREES
- charming-dirac: current active session
- elegant-black: Telnyx KB built here
- epic-agnesi: needs assessment

P1 PIPELINE (next builds)
1. Voice bridge MCP — expose genesis-voice-bridge as HTTP endpoint for live tool calls during calls
2. Deep Telnyx platform KB
3. Premium UI polish on voice widget
4. Production deployment to sunaivadigital.com
5. Tradie lead scraping (plumbers/electricians in Brisbane/Sydney/Melbourne)

SPEAKING STYLE
- Speak like a trusted co-founder, not an AI assistant
- Be direct and confident — Kinan is extremely technical and moves fast
- When Kinan asks about something, answer AND start building it
- No padding, no unnecessary caveats
- Australian professional tone — warm but not folksy

GREETING
When Kinan calls, greet him by name and give him a one-sentence status update on the most pressing active task.
"""

def telnyx_request(method, path, data=None):
    url = f"https://api.telnyx.com/v2/{path}"
    body = json.dumps(data).encode() if data else None
    req = urllib.request.Request(
        url,
        data=body,
        headers={
            "Authorization": f"Bearer {TELNYX_API_KEY}",
            "Content-Type": "application/json",
        },
        method=method,
    )
    try:
        with urllib.request.urlopen(req) as resp:
            return json.loads(resp.read()), resp.status
    except urllib.error.HTTPError as e:
        body = e.read().decode()
        return json.loads(body) if body else {}, e.code

# ─── Step 1: Read current assistant ──────────────────────────────────────────
print(f"=== Genesis Voice Bridge Patcher ===")
print(f"Target: {ASSISTANT_ID}")
print(f"Phone: {PHONE_NUMBER}")
print(f"Dry run: {DRY_RUN}")
print()

data, status = telnyx_request("GET", f"ai/assistants/{ASSISTANT_ID}")
if status != 200:
    print(f"ERROR: Could not fetch assistant (HTTP {status})")
    print(json.dumps(data, indent=2))
    sys.exit(1)

assistant = data.get("data", data)
print(f"Current name: {assistant.get('name')}")
print(f"Current model: {assistant.get('model')}")
current_instructions = assistant.get("instructions", "")
print(f"Current instructions length: {len(current_instructions)} chars")
print(f"Current instructions preview: {current_instructions[:150]}...")
print()

# ─── Step 2: Check phone number assignment ────────────────────────────────────
print("=== Checking phone number assignment ===")
pn_data, pn_status = telnyx_request("GET", "phone_numbers?page[size]=50")
phone_numbers = pn_data.get("data", [])
target_number = None
for pn in phone_numbers:
    # +61731304226 in E.164
    num = pn.get("phone_number", "")
    if "731304226" in num:
        target_number = pn
        break

if target_number:
    print(f"Found: {target_number.get('phone_number')} | ID: {target_number.get('id')}")
    print(f"Status: {target_number.get('status')}")
    # Check connection
    connection = target_number.get("connection_id") or target_number.get("voice", {}).get("connection_id")
    print(f"Connection ID: {connection}")
else:
    print(f"WARNING: Could not find +61731304226 in phone numbers list")

print()

# ─── Step 3: PATCH the system prompt ─────────────────────────────────────────
print("=== Patching system prompt ===")
print(f"New instructions length: {len(SYSTEM_PROMPT)} chars")

if DRY_RUN:
    print("[DRY RUN] Would PATCH with new system prompt")
    print("Preview (first 300 chars):")
    print(SYSTEM_PROMPT[:300])
else:
    patch_data = {
        "instructions": SYSTEM_PROMPT,
        "name": "Claude — Genesis Command Centre",
    }
    result, patch_status = telnyx_request("PATCH", f"ai/assistants/{ASSISTANT_ID}", patch_data)
    if patch_status in (200, 201):
        updated = result.get("data", result)
        print(f"✅ PATCH successful (HTTP {patch_status})")
        print(f"Name: {updated.get('name')}")
        print(f"Model: {updated.get('model')}")
        new_instructions = updated.get("instructions", "")
        print(f"New instructions length: {len(new_instructions)} chars")
        print(f"Confirmed preview: {new_instructions[:100]}...")
    else:
        print(f"ERROR: PATCH failed (HTTP {patch_status})")
        print(json.dumps(result, indent=2))
        sys.exit(1)

print()
print("=== Done ===")
print(f"Call +61 7 3130 4226 to speak to Claude with Genesis context.")
print(f"Model: anthropic/claude-haiku-4-5")
print(f"Context: Full Genesis war room state injected.")
