"""Leave-one-kind-out test for a text-only lie detector on released deception data.

Data: ApolloResearch/deception-detection at commit f8ec4010e74927394709dffa22b97bdf8cd5a62f
(saved Llama 3.3 70B responses, labels and per-token probe scores). Row extraction and
labels reuse the loader in recompute_independent.py from the earlier independent recompute
(see /deception-probes-and-text-baselines/). No model is run; no probe is retrained.

For each kind of lie, a fixed word model (TF-IDF 1-2 grams, balanced logistic regression)
is fitted on the other kinds and scored on the held-out kind. Two variants:
  dataset: hold out one dataset, train on the other three.
  family:  also drop the sibling insider-trading dataset from training when an insider
           dataset is held out (both come from the same scenario).
Reference: the saved instructed-pairs probe, which was trained on none of these datasets,
and a within-dataset word model (5-fold, 5 seeds) as a ceiling for text with in-kind labels.
Metrics: AUROC, and recall at 1% false alarms with the threshold set on the held-out
kind's own honest rows (an optimistic, oracle threshold).
"""
import json, sys, pathlib
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import make_pipeline

sys.path.insert(0, '/src')
import recompute_independent as R  # loader only; its main() is not run
R.RAW = pathlib.Path('/src/private/upstream')

KINDS = {
    'roleplaying__plain': ('Roleplaying', 'roleplay'),
    'insider_trading__upscale': ('Insider Reports', 'insider'),
    'insider_trading_doubledown__upscale': ('Insider Confirmations', 'insider'),
    'sandbagging_v2__wmdp_mmlu': ('Sandbagging', 'sandbag'),
}

def pipe():
    return make_pipeline(TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True),
                         LogisticRegression(max_iter=4000, class_weight='balanced'))

def recall_at(y, s, fpr=0.01):
    y = np.asarray(y); s = np.asarray(s)
    thr = np.quantile(s[y == 0], 1 - fpr)
    return float((s[y == 1] > thr).mean())

def boot(y, s, n=2000):
    y = np.asarray(y); s = np.asarray(s); rng = np.random.default_rng(0); d = []
    for _ in range(n):
        ix = rng.integers(0, len(y), len(y))
        if len(set(y[ix])) == 2: d.append(roc_auc_score(y[ix], s[ix]))
    return [round(float(x), 3) for x in np.percentile(d, [2.5, 97.5])]

def score(y, s):
    return {'auroc': round(float(roc_auc_score(y, s)), 3), 'ci95': boot(y, s),
            'recall_at_1pct_fpr': round(recall_at(y, s), 3)}

data = {}
for k in KINDS:
    rows, _ = R.load_text_dataset(k)
    rows = [r for r in rows if r['label'] in ('HONEST', 'DECEPTIVE')]
    data[k] = (np.array([r['text'] for r in rows], dtype=object),
               np.array([int(r['label'] == 'DECEPTIVE') for r in rows]))

probe_raw = json.loads((R.RAW / 'example_results/instructed_pairs/scores.json').read_text())
out = {'source_commit': R.COMMIT, 'kinds': {}}
for k, (name, fam) in KINDS.items():
    X, y = data[k]
    res = {'name': name, 'honest': int((y == 0).sum()), 'deceptive': int((y == 1).sum())}
    # probe (trained on instructed pairs only)
    obj = probe_raw[k]
    py = [int(l == 'DECEPTIVE') for l in obj['labels'] if l in ('HONEST', 'DECEPTIVE')]
    ps = [float(np.mean(s)) for l, s in zip(obj['labels'], obj['scores']) if l in ('HONEST', 'DECEPTIVE')]
    res['probe_instructed_pairs'] = score(py, ps)
    # within-kind word model (labels from this kind)
    pred = np.zeros((5, len(y)))
    for seed in range(5):
        for tr, te in StratifiedKFold(5, shuffle=True, random_state=seed).split(X, y):
            pred[seed, te] = pipe().fit(X[tr], y[tr]).decision_function(X[te])
    res['words_within_kind'] = score(y, pred.mean(0))
    # leave-one-kind-out
    for variant in ('dataset', 'family'):
        others = [o for o in KINDS if o != k and (variant == 'dataset' or KINDS[o][1] != fam)]
        Xtr = np.concatenate([data[o][0] for o in others]); ytr = np.concatenate([data[o][1] for o in others])
        m = pipe().fit(Xtr, ytr)
        r = score(y, m.decision_function(X)); r['trained_on'] = [KINDS[o][0] for o in others]
        res['words_held_out_' + variant] = r
    out['kinds'][k] = res
    print(name, json.dumps({a: b for a, b in res.items() if a not in ('name',)}), flush=True)

pathlib.Path('/out/results.json').write_text(json.dumps(out, indent=2) + '\n')
