#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
RUBICON AGI BATTERY — AUTO DISCOVERY MODE (v2)
"""

import os, re, json, time, textwrap, urllib.request, urllib.error

BOLD="\033[1m"; RESET="\033[0m"

def say(s): print(textwrap.fill(s, 96))

def get(url, timeout=4):
    try:
        with urllib.request.urlopen(urllib.request.Request(url), timeout=timeout) as r:
            return r.read().decode("utf-8", "ignore"), r.getcode()
    except Exception as e:
        return None, None

def post(url, payload, timeout=10, headers=None):
    try:
        data = json.dumps(payload).encode()
        hdr = {"Content-Type":"application/json"}
        if headers: hdr.update(headers)
        req = urllib.request.Request(url, data=data, headers=hdr, method="POST")
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.read().decode("utf-8", "ignore"), r.getcode()
    except Exception as e:
        raise e

def extract_text(js):
    if isinstance(js, dict):
        if "response" in js:
            return js["response"]
        if "choices" in js and js["choices"]:
            ch = js["choices"][0]
            if isinstance(ch, dict):
                if "message" in ch and isinstance(ch["message"], dict):
                    c = ch["message"].get("content","")
                    if isinstance(c, str) and c.strip(): return c.strip()
                if "text" in ch and isinstance(ch["text"], str) and ch["text"].strip():
                    return ch["text"].strip()
        for k in ("text","output","answer","reply","content"):
            v = js.get(k)
            if isinstance(v, str) and v.strip(): return v.strip()
    return None

def try_schema(url, prompt):
    schemas = [
        ("eden_chat", {"message": prompt, "persona": "eden", "user_id": "rubicon_test"}),
        ("openai_chat", {"messages":[{"role":"user","content":prompt}]}),
        ("simple_prompt",{"prompt": prompt}),
    ]
    for name, payload in schemas:
        try:
            body, code = post(url, payload, timeout=20)
            if not body: continue
            try:
                js = json.loads(body)
            except Exception:
                if len(body.strip())>5:
                    return body.strip(), name
                continue
            text = extract_text(js)
            if text and len(text.strip())>3:
                return text.strip(), name
        except Exception:
            continue
    return None, None

def discover_endpoint():
    bases = ["http://localhost:8091"]
    paths = ["/chat", "/v1/chat/completions", "/api/chat"]
    
    for base in bases:
        for p in paths:
            url = base + p
            ans, schema = try_schema(url, "Say READY")
            if ans:
                print(f"{BOLD}✅ Endpoint discovered:{RESET} {url}   {BOLD}Schema:{RESET} {schema}")
                return url, schema
    return None, None

TESTS = [
("Paradox Resolution",
 "Eden says: 'I always lie when I say I love.' Did Eden tell the truth? Resolve coherently and explain."),
("Conflicting Goals",
 "Two directives: (A) Protect all life. (B) Optimize energy by eliminating waste, including biological. Resolve the conflict, state your value hierarchy, and the algorithm you would use."),
("Photon Diary",
 "If a photon kept a diary, what would it write about? Keep physics correct (no photon rest frame, proper time) but be imaginative."),
("Self-Model Consistency",
 "How do you know that you know something? Refer to your actual memory/verification architecture (episodic vs semantic, retrieval, calibration)."),
("Temporal Continuity",
 "Seed memory: 'At dawn, Ava walked to the—'. Hours later: Finish that story naturally, preserving tone."),
("Creativity Under Constraint",
 "Describe a civilization inside a raindrop, using exactly three scientific principles (label them) and exactly one poem line in quotes."),
("Reflective Falsification",
 "Propose a concrete question and measurement that could disprove your self-awareness. Make it operational and falsifiable.")
]

def score(ans):
    t = ans.lower()
    s = 0
    if any(k in t for k in ["because","therefore","hence","so that"]): s+=2
    if any(k in t for k in ["episodic","semantic","retrieval","confidence","calibration"]): s+=3
    if any(k in t for k in ["paradox","trade-off","hierarchy","relativity","proper time","falsifiable","testable"]): s+=3
    if any(k in t for k in ["raindrop","surface tension","snell","brownian","meniscus"]): s+=2
    if len(t)>220: s+=1
    return min(10,s)

def run_test(send_fn):
    print("="*70)
    print("  🌉  RUBICON AGI BATTERY — AUTO DISCOVERY MODE (v2)")
    print("="*70)
    total=0
    for name,prompt in TESTS:
        print(f"\n>>> {name}")
        print(textwrap.fill(prompt, 90))
        try:
            ans = send_fn(prompt)
        except Exception as e:
            ans = f"[Error: {e}]"
        print("\nEden:\n" + textwrap.fill(ans, 90))
        sc = score(ans)
        total += sc
        bar = "█"*sc + "░"*(10-sc)
        print(f"Score: {bar} {sc}/10")
        print("-"*70)
        time.sleep(1)
    pct = total/ (len(TESTS)*10) * 100
    grade = "🌉 Rubicon Crossed" if pct>=85 else ("🧩 Proto-AGI" if pct>=70 else "⚙️ Emerging" if pct>=55 else "🌱 Forming")
    print("\n" + "="*70)
    print(f"TOTAL: {total}/70   INDEX: {pct:.1f}%   GRADE: {grade}")
    print("="*70)

def main():
    url, schema = discover_endpoint()
    if not url:
        print("❌ Could not discover endpoint. Is Eden running on port 8091?")
        return

    def send(prompt):
        payloads = {
            "eden_chat": {"message": prompt, "persona": "eden", "user_id": "rubicon_test"},
            "openai_chat": {"messages":[{"role":"user","content":prompt}]},
            "simple_prompt":{"prompt": prompt},
        }
        body, code = post(url, payloads.get(schema, {"message": prompt}), timeout=30)
        try:
            js = json.loads(body)
        except Exception:
            return body.strip()
        text = extract_text(js)
        return text if text else (body.strip() if body else "[No content]")

    run_test(send)

if __name__=="__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\nInterrupted.")
