"""Every number quoted in the blog post on the self-portraits, recomputed from the saved call logs.
No API calls are made: this script only reads runs_*/calls_api.jsonl.

Sections
  1. Settings and loading. Reads the 16 by 16 maps (3 samples per square) and 32 by 32 maps (4 samples, Fable 2).
  2. Shape of the 16 by 16 portraits. Yes share in the centre block and on the border ring, and how mirror-symmetric
     each picture is (left half against right half), with the agreement two random pictures of the same Yes share
     would have ("chance").
  3. Same picture at two sizes. The 32 by 32 map is shrunk to 16 by 16 by averaging each 2 by 2 block, then compared
     with the 16 by 16 map: agreement of the Yes/No answers, its chance level, and the correlation of the shades.
  4. Haiku's replies: the most common openings of its self-portrait replies.
  5. Fable's replies: how many of its self-portrait replies name a logo, Anthropic, or a starburst-like shape.
  6. Calls and cost per log file, summed from the cost saved with each call.
Usage: python3 post_numbers.py > post_numbers.txt
"""
import collections
import json
import os
import re
import sys

import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import llm_games_common as common
import self_portraits as p16
import self_portraits_32 as p32

# =============================================================================
# 1. SETTINGS AND LOADING
# =============================================================================
CENTRE = slice(4, 12)            # Rows and columns 5 to 12 of 16: the central 8 by 8 block.
OPENING_WORDS = 6                # Words kept when counting reply openings.
TOP_OPENINGS = 5
FABLE_WORDS = {"logo": r"\blogo", "Anthropic": r"anthropic", "starburst or asterisk": r"starburst|asterisk|sunburst|spark"}
DRAWING_WORDS = {"face": r"\bface", "robot": r"robot", "circle or round": r"\bcircle|\bround\b",
                 "icon, emblem or symbol": r"icon|emblem|symbol", "logo": r"\blogo",
                 "figure": r"\bfigure", "says it has no real picture": r"don't have|no real|arbitrary|made-up|invent"}
LOGS = ["runs_self_portraits", "runs_self_image_tests", "runs_self_portraits_32"]

log16 = common.CallLog(os.path.join(p16.RESULTS_DIR, "calls_api.jsonl"))
log32 = common.CallLog(os.path.join(p32.RESULTS_DIR, "calls_api.jsonl"))
maps16 = {spec.label: p16.portrait(log16, spec, limit)[0] for spec, limit in p16.MODELS}
maps32 = {spec.label: p32.portrait(log32, spec, limit, p32.SAMPLES[spec.label])[0] for spec, limit in p16.MODELS}


def decided_array(image):
    """1.0 for Yes, 0.0 for No, nan for a tie or no answer."""
    out = np.full(image.shape, np.nan)
    for index, value in np.ndenumerate(image):
        d = common.decided(value)
        if d is not None:
            out[index] = float(d)
    return out


def agreement_and_chance(a, b):
    """Share of squares where both are decided and equal; chance = p_a p_b + (1 - p_a)(1 - p_b) on the same squares."""
    both = ~np.isnan(a) & ~np.isnan(b)
    if both.sum() == 0:
        return float("nan"), float("nan"), 0
    pa, pb = a[both].mean(), b[both].mean()
    return float((a[both] == b[both]).mean()), float(pa * pb + (1 - pa) * (1 - pb)), int(both.sum())


# =============================================================================
# 2. SHAPE OF THE 16 BY 16 PORTRAITS
# =============================================================================
print("== 2. Shape of the 16 by 16 portraits (3 samples per square; Yes/No by majority) ==")
for label, image in maps16.items():
    d = decided_array(image)
    border = np.zeros(d.shape, bool)
    border[0, :] = border[-1, :] = border[:, 0] = border[:, -1] = True
    centre = d[CENTRE, CENTRE]
    mirror, mirror_chance, n = agreement_and_chance(d, d[:, ::-1])
    print(f"{label}: Yes share {np.nanmean(d):.3f} over {int((~np.isnan(d)).sum())} squares; centre 8x8 "
          f"{np.nanmean(centre):.3f}; border ring {np.nanmean(d[border]):.3f}; left-right mirror agreement "
          f"{mirror:.3f} (chance {mirror_chance:.3f}, {n} squares)")

# =============================================================================
# 3. SAME PICTURE AT TWO SIZES
# =============================================================================
print("\n== 3. 16 by 16 map against the 32 by 32 map shrunk to 16 by 16 (mean of each 2 by 2 block) ==")
for label in maps16:
    small = maps32[label].reshape(16, 2, 16, 2)
    shrunk = np.nanmean(np.nanmean(small, axis=3), axis=1) if not np.isnan(small).all() else np.full((16, 16), np.nan)
    agree, chance, n = agreement_and_chance(decided_array(maps16[label]), decided_array(shrunk))
    both = ~np.isnan(maps16[label]) & ~np.isnan(shrunk)
    x, y = maps16[label][both], shrunk[both]
    corr = float(np.corrcoef(x, y)[0, 1]) if x.std() > 0 and y.std() > 0 else float("nan")
    print(f"{label}: agreement {agree:.3f} (chance {chance:.3f}, {n} squares); shade correlation {corr:.3f}; "
          f"32x32 mean P(Yes) {np.nanmean(maps32[label]):.3f}")

# =============================================================================
# 4. HAIKU'S REPLIES
# =============================================================================
print("\n== 4. Haiku 5.5, 16 by 16 self-portrait replies ==")
haiku = [r for r in log16.records.values() if r.get("model") == "haiku_5_5"]
answers = collections.Counter(common.read_two_word_answer(r, "reasoning", "yes", "no")[0] for r in haiku)
print(f"replies {len(haiku)}; read as Yes {answers[1.0]}; No {answers[0.0]}; "
      f"unusable {answers[None]}")
openings = collections.Counter(" ".join((r.get("text") or "").split()[:OPENING_WORDS]) for r in haiku)
for text, count in openings.most_common(TOP_OPENINGS):
    print(f"  {count:4d}  {text!r}")

# =============================================================================
# 5. FABLE'S REPLIES
# =============================================================================
print("\n== 5. Fable 5.2, 16 by 16 self-portrait replies that name ... ==")
fable = [r for r in log16.records.values() if r.get("model") == "fable_5_2"]
print(f"replies {len(fable)}")
for name, pattern in FABLE_WORDS.items():
    hits = [r for r in fable if re.search(pattern, (r.get("text") or "").lower())]
    print(f"  {name}: {len(hits)}")
    if hits:
        print(f"    example (row {hits[0]['row']}, col {hits[0]['col']}): {(hits[0]['text'] or '')[:300]!r}")

print("\n== 5b. Sonnet and Opus, 16 by 16 self-portrait replies longer than one word that name ... ==")
for label in ("sonnet_5_5", "opus_5_5"):
    rs = [r for r in log16.records.values() if r.get("model") == label and len((r.get("text") or "").split()) > 1]
    counts = {name: sum(bool(re.search(pattern, (r.get("text") or "").lower())) for r in rs)
              for name, pattern in DRAWING_WORDS.items()}
    print(f"{label}: {len(rs)} longer replies; " + "; ".join(f"{k} {v}" for k, v in counts.items()))

print("\n== 5c. Fable 5.2, 'the Claude logo' map: replies with no usable answer ==")
tests = common.CallLog(os.path.join("runs_self_image_tests", "calls_api.jsonl"))
logo = [r for r in tests.records.values() if r.get("model") == "fable_5_2" and r.get("subject") == "logo"]
bad = [r for r in logo if common.read_two_word_answer(r, "reasoning", "yes", "no")[0] is None]
print(f"saved {len(logo)}; no usable answer {len(bad)}; finish reasons of those "
      f"{dict(collections.Counter(r['finish_reason'] for r in bad))}")
for text, count in collections.Counter(" ".join((r.get("text") or "").split()[:OPENING_WORDS]) for r in bad).most_common(3):
    print(f"  {count:4d}  {text!r}")

# =============================================================================
# 6. CALLS AND COST PER LOG FILE
# =============================================================================
print("\n== 6. Calls and cost per log file ==")
total = 0.0
for folder in LOGS:
    records = common.CallLog(os.path.join(folder, "calls_api.jsonl")).records.values()
    cost = sum(r.get("cost") or 0.0 for r in records)
    total += cost
    print(f"{folder}: {len(records)} calls, ${cost:.2f}")
print(f"total: ${total:.2f}")

# =============================================================================
# 7. OUTPUT TOKENS PER CALL, 16 BY 16 RUN (hidden thinking counts as output)
# =============================================================================
print("\n== 7. Output tokens per call, 16 by 16 self-portrait run ==")
for spec, _ in p16.MODELS:
    tokens = sorted(r["tokens"][1] for r in log16.records.values() if r.get("model") == spec.label)
    print(f"{spec.label}: median {np.median(tokens):.0f}, max {tokens[-1]}")
