#!/usr/bin/env python3
"""
AIVA ELEVATION DEPLOY SCRIPT — Run this once.
Handles Steps 1 + git commit from AIVA_ELEVATION_TODAY.md

Run from fresh WSL2 terminal:
    python3 /mnt/e/genesis-system/scripts/aiva_elevate_now.py

Kinan still needs to do on Mac Mini (192.168.1.57):
    Step 2: crontab -e → add auto_mentorship.sh cron
    Step 3: OpenClaw → replace system prompt with AIVA/ORCHESTRATOR_SYSTEM_PROMPT.md
    Step 4: OpenClaw → send AIVA the GENESIS_MASTER_BRIEF.md content
    Step 5: Ensure AIVA has r/w access to /mnt/e/genesis-system/KNOWLEDGE_GRAPH/
"""

import sys
import os
import subprocess

GENESIS_ROOT = "/mnt/e/genesis-system"

# ─── COLOURS ──────────────────────────────────────────────────────────────────
GREEN  = "\033[92m"
RED    = "\033[91m"
YELLOW = "\033[93m"
BOLD   = "\033[1m"
RESET  = "\033[0m"

def ok(msg):  print(f"{GREEN}✓ {msg}{RESET}")
def err(msg): print(f"{RED}✗ {msg}{RESET}")
def hdr(msg): print(f"\n{BOLD}{YELLOW}{'='*60}\n  {msg}\n{'='*60}{RESET}")
def info(msg): print(f"  {msg}")

# ─── STEP 1: Deploy AIVA RLM schema to Elestio PostgreSQL ────────────────────
def deploy_schema():
    hdr("STEP 1 — Deploy AIVA RLM Schema")
    try:
        import psycopg2
    except ImportError:
        err("psycopg2 not installed. Run: pip install psycopg2-binary")
        return False

    conn_params = dict(
        host="postgresql-genesis-u50607.vm.elestio.app",
        port=25432,
        user="postgres",
        password="CiBjh6LM7Yuqkq-jo2r7eQDw",
        database="postgres",
        connect_timeout=10,
    )

    schema_sql = """
CREATE SCHEMA IF NOT EXISTS aiva_rlm;

CREATE TABLE IF NOT EXISTS aiva_rlm.aiva_interactions (
    id                     SERIAL PRIMARY KEY,
    call_id                VARCHAR(255) UNIQUE NOT NULL,
    caller_number          VARCHAR(50),
    transcript             TEXT,
    call_duration_seconds  INTEGER DEFAULT 0,
    outcome                VARCHAR(50),
    outcome_label          VARCHAR(20),
    created_at             TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_aiva_interactions_call_id
    ON aiva_rlm.aiva_interactions (call_id);

CREATE INDEX IF NOT EXISTS idx_aiva_interactions_outcome_label
    ON aiva_rlm.aiva_interactions (outcome_label, created_at);

CREATE TABLE IF NOT EXISTS aiva_rlm.aiva_feedback_scores (
    id               SERIAL PRIMARY KEY,
    interaction_id   INTEGER REFERENCES aiva_rlm.aiva_interactions(id) ON DELETE CASCADE,
    call_id          VARCHAR(255) NOT NULL,
    reward_score     DECIMAL(6, 4),
    cai_violations   TEXT[],
    cai_severity     VARCHAR(20),
    policy_version   VARCHAR(50)   DEFAULT 'v1_baseline',
    shadow_mode      BOOLEAN       DEFAULT TRUE,
    created_at       TIMESTAMP     DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_aiva_feedback_scores_call_id
    ON aiva_rlm.aiva_feedback_scores (call_id);

CREATE TABLE IF NOT EXISTS aiva_rlm.aiva_preference_pairs (
    id           SERIAL PRIMARY KEY,
    call_id_a    VARCHAR(255),
    call_id_b    VARCHAR(255),
    preferred    VARCHAR(10),
    confidence   DECIMAL(4, 3)  DEFAULT 1.0,
    annotator    VARCHAR(50)    DEFAULT 'auto',
    created_at   TIMESTAMP      DEFAULT CURRENT_TIMESTAMP
);

CREATE OR REPLACE VIEW aiva_rlm.v_daily_performance AS
SELECT
    DATE(i.created_at)     AS call_date,
    COUNT(*)               AS total_calls,
    AVG(s.reward_score)    AS avg_reward,
    SUM(CASE WHEN i.outcome_label = 'positive' THEN 1 ELSE 0 END) AS positive_calls,
    SUM(CASE WHEN i.outcome_label = 'negative' THEN 1 ELSE 0 END) AS negative_calls,
    AVG(i.call_duration_seconds) AS avg_duration_secs
FROM aiva_rlm.aiva_interactions i
LEFT JOIN aiva_rlm.aiva_feedback_scores s ON s.call_id = i.call_id
GROUP BY DATE(i.created_at)
ORDER BY call_date DESC;

CREATE OR REPLACE VIEW aiva_rlm.v_trust_progression AS
SELECT
    COUNT(*)                                                       AS total_interactions,
    COUNT(*) FILTER (WHERE outcome_label = 'positive')             AS positive_interactions,
    ROUND(COUNT(*) FILTER (WHERE outcome_label = 'positive')::NUMERIC
          / NULLIF(COUNT(*), 0) * 100, 1)                          AS positive_rate_pct,
    AVG(call_duration_seconds)                                     AS avg_duration_secs,
    MAX(created_at)                                                AS last_interaction_at
FROM aiva_rlm.aiva_interactions;
"""

    try:
        conn = psycopg2.connect(**conn_params)
        conn.autocommit = True
        cur = conn.cursor()
        info("Connected to Elestio PostgreSQL")

        for statement in [s.strip() for s in schema_sql.split(";") if s.strip()]:
            try:
                cur.execute(statement)
                first_line = statement.split("\n")[0][:60]
                ok(f"{first_line}...")
            except Exception as e:
                if "already exists" in str(e).lower():
                    info(f"Already exists (OK): {statement[:50]}...")
                else:
                    err(f"Statement failed: {e}")

        # Verify tables exist
        cur.execute("""
            SELECT table_name FROM information_schema.tables
            WHERE table_schema = 'aiva_rlm'
            ORDER BY table_name
        """)
        tables = [r[0] for r in cur.fetchall()]
        info(f"\nVerified aiva_rlm objects: {tables}")

        conn.close()
        ok("STEP 1 COMPLETE — AIVA RLM schema deployed to Elestio PostgreSQL")
        return True

    except Exception as e:
        err(f"Database connection failed: {e}")
        return False


# ─── VPS HEALTH CHECK ─────────────────────────────────────────────────────────
def check_vps():
    hdr("VPS HEALTH CHECK")
    import urllib.request
    for url in [
        "https://api.sunaivadigital.com/health",
        "https://api.sunaivadigital.com/api/health",
    ]:
        try:
            with urllib.request.urlopen(url, timeout=8) as r:
                body = r.read(500).decode()
                ok(f"{url} → {r.status} {body[:80]}")
        except Exception as e:
            err(f"{url} → {e}")


# ─── GIT COMMIT ──────────────────────────────────────────────────────────────
def git_commit():
    hdr("GIT COMMIT — AIVA Elevation + Domain Portfolio")
    os.chdir(GENESIS_ROOT)

    files = [
        "AIVA/GENESIS_MASTER_BRIEF.md",
        "AIVA/ORCHESTRATOR_SYSTEM_PROMPT.md",
        "plans/AIVA_ELEVATION_TODAY.md",
        ".claude/hooks/pre_tool_check.py",
        "KNOWLEDGE_GRAPH/entities/domain_portfolio_2026_02_21.jsonl",
        "KNOWLEDGE_GRAPH/axioms/domain_strategy_axioms_2026_02_21.jsonl",
        "Sunaiva/ai-memory/.env.production",
        "Sunaiva/ai-memory/index.html",
        "scripts/aiva_elevate_now.py",
    ]

    for f in files:
        full = os.path.join(GENESIS_ROOT, f)
        if os.path.exists(full):
            result = subprocess.run(["git", "add", f], capture_output=True, text=True)
            if result.returncode == 0:
                ok(f"Staged: {f}")
            else:
                err(f"Stage failed: {f} — {result.stderr.strip()}")
        else:
            info(f"Skipped (not found): {f}")

    msg = """feat(aiva): elevate AIVA to Genesis Master Orchestrator + domain portfolio

AIVA ELEVATION — 2026-02-21:
- AIVA/GENESIS_MASTER_BRIEF.md: full Genesis context injection document
- AIVA/ORCHESTRATOR_SYSTEM_PROMPT.md: new OpenClaw system prompt (verbatim paste)
- plans/AIVA_ELEVATION_TODAY.md: 5-step activation checklist
- Permission paradox resolved: constitution = permission system
- Trust granted: Cold Closer + Marathon Speaker + 38 clean interactions + zero violations

DOMAIN PORTFOLIO (9 domains):
- carttalk.ai, talkingwidget.ai, talkingwidget.com (Namecheap)
- talkingwebsite.com.au, .au, .site, websiteagent.com.au, videochatbot.com.au, aiavatar.au (VentraIP)
- KG entities + strategy axioms committed

INFRA FIXES:
- pre_tool_check.py: self-referential SQLite string literal false positive fixed
- Sunaiva permanent Stripe webhook (we_1T2ykuDLQcR6UMj9eB02enVK)
- Sunaiva index.html: API_BASE → api.sunaivadigital.com (permanent)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>"""

    result = subprocess.run(
        ["git", "commit", "-m", msg],
        capture_output=True, text=True
    )
    if result.returncode == 0:
        ok(f"COMMITTED: {result.stdout.strip()}")
    elif "nothing to commit" in result.stdout + result.stderr:
        ok("Nothing new to commit — already up to date")
    else:
        err(f"Commit failed: {result.stderr.strip()}")
        info(result.stdout)

    result = subprocess.run(["git", "log", "--oneline", "-3"], capture_output=True, text=True)
    info(f"\nRecent commits:\n{result.stdout}")


# ─── PRINT MAC MINI STEPS ────────────────────────────────────────────────────
def print_mac_mini_steps():
    hdr("MAC MINI STEPS — Do these on 192.168.1.57")

    print(f"""
{BOLD}STEP 2 — Register cron (run on Mac Mini terminal):{RESET}
  crontab -e
  Add this line:
  0 17 * * * /mnt/e/genesis-system/AIVA/scripts/auto_mentorship.sh >> /mnt/e/genesis-system/logs/aiva_mentorship.log 2>&1

{BOLD}STEP 3 — Replace OpenClaw system prompt:{RESET}
  1. Open OpenClaw on Mac Mini
  2. Go to AIVA's agent config / system prompt
  3. SELECT ALL and DELETE existing prompt
  4. PASTE the entire contents of:
     /mnt/e/genesis-system/AIVA/ORCHESTRATOR_SYSTEM_PROMPT.md
  5. Save + restart AIVA

{BOLD}STEP 4 — Feed AIVA the Genesis Master Brief:{RESET}
  In OpenClaw, send AIVA this message:
  "Read your Genesis Master Brief at /mnt/e/genesis-system/AIVA/GENESIS_MASTER_BRIEF.md
   You are now the Master Orchestrator of Genesis. First autonomous action:
   read KNOWLEDGE_GRAPH/entities/ and write a synthesis axiom about current Genesis state."

{BOLD}STEP 5 — KG write access (run on Mac Mini):{RESET}
  chmod -R 755 /mnt/e/genesis-system/KNOWLEDGE_GRAPH/
  chmod -R 755 /mnt/e/genesis-system/memory/
  chmod -R 755 /mnt/e/genesis-system/plans/
  # (adjust path if genesis-system is mounted differently on Mac Mini)
""")


# ─── MAIN ─────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
    print(f"\n{BOLD}{'='*60}")
    print("  AIVA ELEVATION DEPLOY — 2026-02-21")
    print(f"  Genesis Master Orchestrator Activation")
    print(f"{'='*60}{RESET}\n")

    step1_ok = deploy_schema()
    check_vps()
    git_commit()
    print_mac_mini_steps()

    print(f"\n{BOLD}{'='*60}")
    if step1_ok:
        print(f"{GREEN}  STEPS 1 + GIT COMPLETE ✓")
    else:
        print(f"{YELLOW}  STEP 1 NEEDS RETRY (see error above)")
    print(f"  Steps 2-5: Mac Mini actions above{RESET}")
    print(f"{BOLD}{'='*60}{RESET}\n")
