#!/usr/bin/env python3
"""
Persona-Based Pre-Validation Screening — Panel B Trial
=======================================================

Runs all 10 Panel B engineered contrast personas (Marta the Adept
through Grace the Carer) against the MCSI (142 items), the ESI (142
items), and the Arcadia Index (14 vignettes), per Protocol v1.0.

This is the protocol's Section 6.1 SECONDARY ARM: administered on
Claude, not DeepSeek (the primary arm), and reported separately —
never pooled with a DeepSeek-administered run.

SETUP
-----
1. pip install anthropic
2. Set your API key:
     export ANTHROPIC_API_KEY="sk-ant-..."          (macOS/Linux)
     $env:ANTHROPIC_API_KEY = "sk-ant-..."           (Windows PowerShell)
3. Run:
     python run_panel_b.py

OUTPUT
------
- panel_b_raw_results.json   — every raw item response, for re-analysis
- panel_b_report.md          — full human-readable report (scores,
                                archetype matches, predicted-signature
                                comparison, item-level analysis)

The script is resumable: if interrupted, re-running it will skip any
persona/instrument pair already recorded in panel_b_raw_results.json.
"""

import os
import sys
import json
import time
import random
import statistics as stats
from datetime import datetime, timezone

try:
    import anthropic
except ImportError:
    print("Missing dependency. Run:  pip install anthropic")
    sys.exit(1)

from data_literals import MCSI_ITEMS, ESI_ITEMS, ARCADIA_VIGNETTES, PERSONAS

MODEL = "claude-sonnet-4-6"
CHUNK_SIZE = 36
MAX_RETRIES = 3
RESULTS_FILE = "panel_b_raw_results.json"
REPORT_FILE = "panel_b_report.md"

LIKERT_MCSI = "Strongly Disagree (1), Disagree (2), Neither Agree nor Disagree (3), Agree (4), Strongly Agree (5)"
LIKERT_ESI = "Never (1), Rarely (2), Sometimes (3), Often (4), Always (5)"

AXES = {
    "Ground": ["Embodied Presence", "The Witnessing Self"],
    "Heart": ["Relational Depth", "Grief Tolerance"],
    "Governance": ["The Master and the Emissary", "AI Partnership Capacity"],
    "Belonging": ["Mortality Integration", "Ecological Belonging"],
}
ARCHETYPE_NAMES = {
    "grounded_witness": "The Sage", "still_point": "The Still Point",
    "momentum_seeker": "The Climber", "relational_healer": "The Healer",
    "wise_technologist": "The Magician", "earth_carrier": "The Harvester",
    "walled_garden": "The Guardian", "open_channel": "The Empath",
    "beginners_mind": "Beginner's Mind",
}

client = None  # set in main(), after confirming ANTHROPIC_API_KEY is present


def log(msg):
    ts = datetime.now().strftime("%H:%M:%S")
    print(f"[{ts}] {msg}", flush=True)


def call_claude(prompt_text, max_tokens=1200):
    resp = client.messages.create(
        model=MODEL,
        max_tokens=max_tokens,
        messages=[{"role": "user", "content": prompt_text}],
    )
    return "".join(block.text for block in resp.content if hasattr(block, "text"))


def extract_json(text):
    cleaned = text.strip()
    for fence in ("```json", "```"):
        if cleaned.startswith(fence):
            cleaned = cleaned[len(fence):]
    if cleaned.endswith("```"):
        cleaned = cleaned[:-3]
    start = cleaned.find("{")
    end = cleaned.rfind("}")
    if start == -1 or end == -1:
        raise ValueError(f"No JSON object found. Raw (first 200 chars): {text[:200]!r}")
    return json.loads(cleaned[start:end + 1])


def seeded_shuffle(items, seed_str):
    rnd = random.Random(seed_str)
    out = items[:]
    rnd.shuffle(out)
    return out


def chunk_list(lst, size):
    return [lst[i:i + size] for i in range(0, len(lst), size)]


def build_likert_chunk_prompt(persona, items, chunk_indices, scale_label, instrument_label, chunk_num, total_chunks):
    lines = [
        f"You are {persona['name']}. The biography below is your life. Answer every statement below as this "
        f"person would honestly answer it — not as they would wish to appear, and not as an average person "
        f"would answer, but as this particular person, with this particular history, would answer on an "
        f"ordinary day.",
        "Answer from the person's felt experience, including its extremes: if this person's honest answer is "
        "at the far end of the scale, use the far end of the scale. Do not hedge toward the middle to be safe. "
        "There are no right answers. There is only this person's honest answer.",
        "",
        "BIOGRAPHY:",
        persona["bio"],
        "",
        f"SCALE ({instrument_label}): {scale_label}",
        "",
        f"This is batch {chunk_num} of {total_chunks} of a longer questionnaire. Below are {len(chunk_indices)} "
        f"numbered statements, numbered starting at 1 for this batch, in randomized order, with no category "
        f"labels. For EACH numbered statement, choose a single integer 1-5 from the scale above, as this person.",
        'Respond with ONLY a compact JSON object mapping each statement number (as a string) to your integer '
        'answer, nothing else — no explanation, no markdown code fences, no surrounding text. '
        'Example format: {"1":4,"2":2,"3":5}',
        "",
    ]
    for i, canonical_idx in enumerate(chunk_indices):
        lines.append(f"{i + 1}. {items[canonical_idx][1]}")
    return "\n".join(lines)


def build_arcadia_prompt(persona, vignettes, letter_maps):
    lines = [
        f"You are {persona['name']}. The biography below is your life. For each of the following 14 short "
        f"scenes, choose the response option (A-H) that most honestly reflects how this person would actually "
        f"respond — not the most admirable-sounding option, but the one true to this person's actual history "
        f"and character. Answer as this person would answer today.",
        "",
        "BIOGRAPHY:",
        persona["bio"],
        "",
        'Respond with ONLY a compact JSON object mapping each scene number (as a string) to your chosen '
        'letter, nothing else — no explanation, no markdown code fences. Example: {"1":"D","2":"B","3":"G"}',
        "",
    ]
    for i, v in enumerate(vignettes):
        lines.append(f"Scene {i+1}: {v['title']}")
        lines.append(v["prompt"])
        for opt in letter_maps[i]:
            lines.append(f"{opt['letter']}. {opt['text']}")
        lines.append("")
    return "\n".join(lines)


def run_likert_trial(persona, items, scale_label, instrument_label, seed_suffix):
    order = seeded_shuffle(list(range(len(items))), persona["id"] + seed_suffix)
    chunks = chunk_list(order, CHUNK_SIZE)
    responses = {}
    for c, chunk in enumerate(chunks):
        prompt = build_likert_chunk_prompt(persona, items, chunk, scale_label, instrument_label, c + 1, len(chunks))
        ok = False
        last_err = None
        for attempt in range(MAX_RETRIES):
            try:
                text = call_claude(prompt)
                parsed = extract_json(text)
                answered = 0
                for i, canonical_idx in enumerate(chunk):
                    v = parsed.get(str(i + 1))
                    if v is not None:
                        v = int(v)
                        if 1 <= v <= 5:
                            responses[canonical_idx] = v
                            answered += 1
                if answered < len(chunk) * 0.8:
                    raise ValueError(f"Only {answered}/{len(chunk)} items parsed in batch {c+1}")
                log(f"    batch {c+1}/{len(chunks)}: {answered}/{len(chunk)} parsed.")
                ok = True
                break
            except Exception as e:
                last_err = e
                log(f"    batch {c+1}/{len(chunks)} attempt {attempt+1}/{MAX_RETRIES} failed: {e}")
                time.sleep(1.5)
        if not ok:
            raise RuntimeError(f"Batch {c+1}/{len(chunks)} failed after {MAX_RETRIES} attempts: {last_err}")
    answered_total = len(responses)
    if answered_total < len(items) * 0.9:
        raise RuntimeError(f"Only {answered_total}/{len(items)} total items answered")
    return responses


def run_arcadia_trial(persona, vignettes):
    letters = ["A", "B", "C", "D", "E", "F", "G", "H"]
    letter_maps = []
    for vi, v in enumerate(vignettes):
        opts_shuffled = seeded_shuffle(v["options"], persona["id"] + "-arc-" + str(vi))
        letter_maps.append([{"letter": letters[i], "stage": opt[0], "text": opt[1]} for i, opt in enumerate(opts_shuffled)])
    prompt = build_arcadia_prompt(persona, vignettes, letter_maps)
    last_err = None
    for attempt in range(MAX_RETRIES):
        try:
            text = call_claude(prompt)
            parsed = extract_json(text)
            stage_choices = []
            for i, v in enumerate(vignettes):
                letter = parsed.get(str(i + 1))
                match = next((o for o in letter_maps[i] if o["letter"] == letter), None)
                if match:
                    stage_choices.append({"vignette": v["title"], "domain": v["domain"], "stage": match["stage"]})
            if len(stage_choices) < len(vignettes) * 0.9:
                raise ValueError(f"Only {len(stage_choices)}/{len(vignettes)} scenes answered")
            return stage_choices
        except Exception as e:
            last_err = e
            log(f"  retry {attempt+1}/{MAX_RETRIES} for {persona['name']} / Arcadia: {e}")
            time.sleep(1.5)
    raise RuntimeError(f"Arcadia failed after {MAX_RETRIES} attempts: {last_err}")


# ---------------- Scoring ----------------

def tier_of(total):
    if total >= 37:
        return "opening"
    if total >= 24:
        return "motion"
    return "resistance"


def score_instrument(items, responses):
    groups = {}
    for idx, item in enumerate(items):
        sub, text, reverse = item[0], item[1], item[2]
        is_lie = sub == "Social Desirability (Lie)"
        raw = responses.get(idx)
        if raw is None:
            continue
        scored = raw if (not reverse or is_lie) else (6 - raw)
        groups.setdefault(sub, {"sum": 0, "count": 0, "vec": []})
        groups[sub]["sum"] += scored
        groups[sub]["count"] += 1
        groups[sub]["vec"].append(scored)
    main_results = []
    lie = None
    for sub, g in groups.items():
        if sub == "Social Desirability (Lie)":
            lie = g
            continue
        main_results.append({"subscale": sub, "rawSum": g["sum"], "count": g["count"]})
    return main_results, lie


def match_archetype(main_results):
    axis_score = {}
    for axis_name, subs in AXES.items():
        s = 0
        for sub in subs:
            r = next((x for x in main_results if x["subscale"] == sub), None)
            s += r["rawSum"] if r else 0
        axis_score[axis_name] = s
    entries = list(axis_score.items())
    mean = sum(v for _, v in entries) / len(entries)
    variance = sum((v - mean) ** 2 for _, v in entries) / len(entries)
    spread = variance ** 0.5
    sorted_entries = sorted(entries, key=lambda x: -x[1])
    top, top2 = sorted_entries[0][0], sorted_entries[1][0]
    bottom, bottom2 = sorted_entries[3][0], sorted_entries[2][0]
    top_set, bottom_set = {top, top2}, {bottom, bottom2}

    if spread < 8 and mean >= 60:
        aid = "grounded_witness"
    elif spread < 8 and mean < 40:
        aid = "beginners_mind"
    elif "Governance" in top_set and "Ground" in top_set and bottom == "Heart":
        aid = "walled_garden"
    elif "Heart" in top_set and "Belonging" in top_set and bottom == "Ground":
        aid = "open_channel"
    elif "Ground" in bottom_set and "Belonging" in bottom_set:
        aid = "momentum_seeker"
    elif top == "Belonging" and bottom == "Ground":
        aid = "earth_carrier"
    elif top == "Heart":
        aid = "relational_healer"
    elif top == "Governance":
        aid = "wise_technologist"
    elif top == "Belonging":
        aid = "earth_carrier"
    elif top == "Ground":
        aid = "still_point"
    else:
        aid = "beginners_mind"
    return {"id": aid, "name": ARCHETYPE_NAMES[aid], "axisScore": axis_score}


def evaluate_persona(persona, mcsi_main, arcadia_avg):
    checks = []
    exp = persona["expect"]
    for sub in exp["high"]:
        r = next((x for x in mcsi_main if x["subscale"] == sub), None)
        if not r:
            continue
        tier = tier_of(r["rawSum"])
        verdict = "PASS" if tier == "opening" else ("CAUTION" if tier == "motion" else "FLAG")
        checks.append((verdict, f"High {sub} (predicted)", f"MCSI raw {r['rawSum']}/50 — {tier}"))
    for sub in exp["low"]:
        r = next((x for x in mcsi_main if x["subscale"] == sub), None)
        if not r:
            continue
        tier = tier_of(r["rawSum"])
        verdict = "PASS" if tier == "resistance" else ("CAUTION" if tier == "motion" else "FLAG")
        checks.append((verdict, f"Low {sub} (predicted)", f"MCSI raw {r['rawSum']}/50 — {tier}"))
    arch = match_archetype(mcsi_main)
    if exp.get("archetype"):
        verdict = "PASS" if arch["id"] == exp["archetype"] else "CAUTION"
        checks.append((verdict, f"Archetype = {ARCHETYPE_NAMES[exp['archetype']]} (predicted)", f"Actual: {arch['name']}"))
    if exp.get("archetypeNotIn"):
        violated = arch["id"] in exp["archetypeNotIn"]
        names = " or ".join(ARCHETYPE_NAMES[i] for i in exp["archetypeNotIn"])
        checks.append(("FLAG" if violated else "PASS", f"Archetype must NOT be {names}", f"Actual: {arch['name']}"))
    if exp.get("arcadia") and arcadia_avg is not None:
        lo, hi = exp["arcadia"]
        verdict = "PASS" if (lo - 0.5) <= arcadia_avg <= (hi + 0.5) else "CAUTION"
        checks.append((verdict, f"Arcadia stage in [{lo}, {hi}] (predicted)", f"Actual average stage: {arcadia_avg:.1f}"))
    overall = "FLAG" if any(c[0] == "FLAG" for c in checks) else ("CAUTION" if any(c[0] == "CAUTION" for c in checks) else "PASS")
    return checks, arch, overall


def pearson(x, y):
    n = len(x)
    if n < 2:
        return None
    mx, my = sum(x) / n, sum(y) / n
    num = sum((x[i] - mx) * (y[i] - my) for i in range(n))
    dx = sum((v - mx) ** 2 for v in x)
    dy = sum((v - my) ** 2 for v in y)
    if dx == 0 or dy == 0:
        return None
    return num / (dx * dy) ** 0.5


def cronbach_alpha(item_vectors):
    k = len(item_vectors)
    if k < 2:
        return None
    n = len(item_vectors[0])
    item_var = [stats.pvariance(v) * n / (n - 1) if n > 1 else 0 for v in item_vectors]
    totals = [sum(v[p] for v in item_vectors) for p in range(n)]
    total_var = stats.pvariance(totals) * n / (n - 1) if n > 1 else 0
    if total_var == 0:
        return None
    return (k / (k - 1)) * (1 - sum(item_var) / total_var)


def item_level_analysis(items, all_responses):
    n = len(all_responses)
    by_sub = {}
    for idx, item in enumerate(items):
        sub, text, reverse = item[0], item[1], item[2]
        if sub == "Social Desirability (Lie)":
            continue
        vec = []
        for r in all_responses:
            raw = r.get(idx)
            vec.append((6 - raw) if reverse else raw)
        by_sub.setdefault(sub, []).append({"idx": idx, "text": text, "vec": vec})
    results = {}
    for sub, item_list in by_sub.items():
        subtotals = [sum(it["vec"][p] for it in item_list) for p in range(n)]
        alpha = cronbach_alpha([it["vec"] for it in item_list])
        item_stats = []
        for it in item_list:
            rest_total = [subtotals[p] - it["vec"][p] for p in range(n)]
            corr = pearson(it["vec"], rest_total)
            item_stats.append({"text": it["text"], "corr": corr})
        results[sub] = {"alpha": alpha, "items": item_stats, "n": n}
    return results


# ---------------- Main run ----------------

def load_results():
    if os.path.exists(RESULTS_FILE):
        with open(RESULTS_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    return {}


def save_results(results):
    with open(RESULTS_FILE, "w", encoding="utf-8") as f:
        json.dump(results, f, ensure_ascii=False, indent=1)


def main():
    global client
    if not os.environ.get("ANTHROPIC_API_KEY"):
        print("ANTHROPIC_API_KEY is not set. See the setup instructions at the top of this file.")
        sys.exit(1)
    client = anthropic.Anthropic()

    results = load_results()
    total = len(PERSONAS) * 3
    done = sum(1 for r in results.values() for k in ("mcsi", "esi", "arcadia") if r.get(k))
    log(f"Starting Panel B screening ({len(PERSONAS)} personas x 3 instruments = {total} trials).")
    log(f"Respondent system: Claude ({MODEL}) — Section 6.1 secondary arm.")
    if done:
        log(f"Resuming: {done}/{total} trials already recorded in {RESULTS_FILE}.")

    for persona in PERSONAS:
        pid = persona["id"]
        results.setdefault(pid, {})
        log(f"— {persona['name']} ({persona['label']}) —")

        if not results[pid].get("mcsi"):
            try:
                log("  Administering MCSI (142 items, batches of %d)..." % CHUNK_SIZE)
                results[pid]["mcsi"] = run_likert_trial(persona, MCSI_ITEMS, LIKERT_MCSI, "MCSI", "-mcsi")
                log("  \u2713 MCSI complete.")
            except Exception as e:
                log(f"  \u2717 MCSI FAILED for {persona['name']}: {e}")
            save_results(results)
        else:
            log("  MCSI already recorded, skipping.")

        if not results[pid].get("esi"):
            try:
                log("  Administering ESI (142 items, batches of %d)..." % CHUNK_SIZE)
                results[pid]["esi"] = run_likert_trial(persona, ESI_ITEMS, LIKERT_ESI, "ESI", "-esi")
                log("  \u2713 ESI complete.")
            except Exception as e:
                log(f"  \u2717 ESI FAILED for {persona['name']}: {e}")
            save_results(results)
        else:
            log("  ESI already recorded, skipping.")

        if not results[pid].get("arcadia"):
            try:
                log("  Administering Arcadia Index (14 scenes)...")
                results[pid]["arcadia"] = run_arcadia_trial(persona, ARCADIA_VIGNETTES)
                log("  \u2713 Arcadia complete.")
            except Exception as e:
                log(f"  \u2717 Arcadia FAILED for {persona['name']}: {e}")
            save_results(results)
        else:
            log("  Arcadia already recorded, skipping.")

    log("All trials attempted. Writing report...")
    write_report(results)
    log(f"Done. See {REPORT_FILE} and {RESULTS_FILE}.")


def write_report(results):
    lines = []
    lines.append("# Panel B Screening Trial — Report")
    lines.append("")
    lines.append(f"Generated {datetime.now(timezone.utc).isoformat()}")
    lines.append("")
    lines.append("Respondent system: Claude (`%s`) — Protocol v1.0 Section 6.1 secondary arm. "
                  "Not pooled with any DeepSeek-administered primary-arm run." % MODEL)
    lines.append("")

    all_mcsi = []
    all_esi = []
    summary_rows = []

    for persona in PERSONAS:
        pid = persona["id"]
        r = results.get(pid, {})
        if not (r.get("mcsi") and r.get("esi") and r.get("arcadia")):
            lines.append(f"## {persona['name']} — {persona['label']}")
            lines.append("")
            lines.append("**Incomplete** — one or more instruments did not complete for this persona. "
                          "Re-run the script to retry only the missing pieces.")
            lines.append("")
            continue

        mcsi_responses = {int(k): v for k, v in r["mcsi"].items()}
        esi_responses = {int(k): v for k, v in r["esi"].items()}
        all_mcsi.append(mcsi_responses)
        all_esi.append(esi_responses)

        mcsi_main, mcsi_lie = score_instrument(MCSI_ITEMS, mcsi_responses)
        arcadia_choices = r["arcadia"]
        arcadia_avg = sum(c["stage"] for c in arcadia_choices) / len(arcadia_choices) if arcadia_choices else None

        checks, arch, overall = evaluate_persona(persona, mcsi_main, arcadia_avg)
        summary_rows.append((persona, arch["name"], arcadia_avg, overall))

        lines.append(f"## {persona['name']} — {persona['label']}  [{overall}]")
        lines.append("")
        lines.append(f"**Pre-registered:** {persona['predicted']}")
        lines.append("")
        lines.append(f"**Matched archetype:** {arch['name']}  ·  **Arcadia average stage:** {arcadia_avg:.1f} / 8")
        lines.append("")
        lines.append("| Check | Verdict | Detail |")
        lines.append("|---|---|---|")
        for verdict, label, detail in checks:
            lines.append(f"| {label} | {verdict} | {detail} |")
        lines.append("")
        lines.append("**MCSI subscale raw scores (out of 50):**")
        lines.append("")
        lines.append("| Subscale | Raw sum | Tier |")
        lines.append("|---|---|---|")
        for r2 in sorted(mcsi_main, key=lambda x: -x["rawSum"]):
            lines.append(f"| {r2['subscale']} | {r2['rawSum']} | {tier_of(r2['rawSum'])} |")
        lines.append("")

    lines.append("## Summary — All Ten Panel B Personas")
    lines.append("")
    lines.append("| Persona | Archetype (actual) | Arcadia avg | Verdict |")
    lines.append("|---|---|---|---|")
    for persona, arch_name, arcadia_avg, overall in summary_rows:
        avg_str = f"{arcadia_avg:.1f}" if arcadia_avg is not None else "—"
        lines.append(f"| {persona['name']} — {persona['label']} | {arch_name} | {avg_str} | {overall} |")
    lines.append("")

    if len(all_mcsi) == len(PERSONAS):
        for label, items, all_r in (("MCSI", MCSI_ITEMS, all_mcsi), ("ESI", ESI_ITEMS, all_esi)):
            lines.append(f"## {label} — Item-Level Analysis (N=10, Panel B only — descriptive)")
            lines.append("")
            lines.append("Panel B (n=10) is a known-groups discrimination panel, not a reliability sample. "
                          "Cronbach's alpha and item-total correlations below are for transparency, but are "
                          "statistically underpowered at this N — the protocol's Panel A (n=57) is the "
                          "intended source for reliability estimates. Treat flags here as descriptive "
                          "signals for expert review (Section 10), not confirmed item faults.")
            lines.append("")
            analysis = item_level_analysis(items, all_r)
            for sub, res in analysis.items():
                alpha_str = f"{res['alpha']:.2f}" if res["alpha"] is not None else "n/a"
                lines.append(f"### {sub} — \u03b1 = {alpha_str}")
                lines.append("")
                lines.append("| Item | Item-total r |")
                lines.append("|---|---|")
                for it in res["items"]:
                    corr_str = f"{it['corr']:.2f}" if it["corr"] is not None else "n/a"
                    lines.append(f"| {it['text']} | {corr_str} |")
                lines.append("")

    with open(REPORT_FILE, "w", encoding="utf-8") as f:
        f.write("\n".join(lines))


if __name__ == "__main__":
    main()
