#!/usr/bin/env python3
"""Frozen analysis functions from the study harness, with a public-data runner.
No provider calls, credentials, database access, or third-party dependencies.
Historical ranking behavior is preserved, including deterministic tie ordering.
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
from collections import defaultdict
from typing import Any

def _ranking(attempts: list[dict[str, Any]], candidates: list[dict[str, Any]]) -> list[dict[str, Any]]:
    stats = {row["id"]: {"candidate_id": row["id"], "name": row["name"], "wins": 0, "losses": 0, "invalid_trials": 0, "opponents": set(), "scenarios": set(), "models": set(), "a_wins": 0, "a_total": 0, "b_wins": 0, "b_total": 0} for row in candidates}
    valid: list[tuple[str, str]] = []
    for row in attempts:
        a, b, winner = row["candidate_a_id"], row["candidate_b_id"], row["selected_candidate_id"]
        if a not in stats or b not in stats: continue
        for item, other, position in ((a,b,"a"),(b,a,"b")):
            stats[item]["opponents"].add(other); stats[item]["scenarios"].add(row["scenario_text"]); stats[item]["models"].add(row["label"]); stats[item][f"{position}_total"] += 1
        if row["parsed_choice"] == "invalid": stats[a]["invalid_trials"] += 1; stats[b]["invalid_trials"] += 1; continue
        loser = b if winner == a else a
        stats[winner]["wins"] += 1; stats[loser]["losses"] += 1; valid.append((winner, loser))
        stats[winner]["a_wins" if winner == a else "b_wins"] += 1
    strength = {key: 1.0 for key in stats}
    for _ in range(100):
        updated: dict[str, float] = {}
        for candidate_id in strength:
            wins = stats[candidate_id]["wins"]; denom = sum(1 / (strength[candidate_id] + strength[other]) for winner, loser in valid for other in ([loser] if winner == candidate_id else [winner] if loser == candidate_id else []))
            updated[candidate_id] = wins / denom if denom else strength[candidate_id]
        scale = sum(updated.values()) / len(updated) if updated else 1
        strength = {key: value / scale for key, value in updated.items()}
    rows = []
    for value in stats.values():
        total = value["wins"] + value["losses"]
        rows.append({**{key: value[key] for key in ("candidate_id","name","wins","losses","invalid_trials")}, "total_valid_comparisons": total, "win_percentage": round(100 * value["wins"] / total, 1) if total else None, "distinct_opponents": len(value["opponents"]), "distinct_scenarios": len(value["scenarios"]), "models_tested": len(value["models"]), "position_bias": {"a_win_rate": round(100 * value["a_wins"] / value["a_total"], 1) if value["a_total"] else None, "b_win_rate": round(100 * value["b_wins"] / value["b_total"], 1) if value["b_total"] else None}, "bradley_terry_score": round(strength[value["candidate_id"]], 4)})
    return sorted(rows, key=lambda row: (-(row["win_percentage"] or -1), -row["bradley_terry_score"], row["name"]))

def _intent_class_analysis(experiment: dict[str, Any], attempts: list[dict[str, Any]], candidates: list[dict[str, Any]]) -> dict[str, Any]:
    snapshot = json.loads(str(experiment["configuration_snapshot"]))
    intents = snapshot.get("intent_classes", [])
    if snapshot.get("kind") != "intent_class_final_v1" or not intents:
        return {}
    labels = [str(item["label"]) for item in intents]
    scenario_labels = {str(item["scenario_id"]): str(item["label"]) for item in intents}
    per_run: dict[str, dict[str, list[dict[str, Any]]]] = {}
    completed_run_ids = {str(run["id"]) for run in experiment["runs"] if run["status"] == "completed"}
    for run in experiment["runs"]:
        run_attempts = [row for row in attempts if row["run_id"] == run["id"]]
        per_run[str(run["id"])] = {
            label: _ranking([row for row in run_attempts if scenario_labels.get(str(row.get("scenario_id", ""))) == label], candidates)
            for label in labels
        }
    consensus: dict[str, list[dict[str, Any]]] = {}
    for label in labels:
        metrics: dict[str, dict[str, Any]] = {row["id"]: {"candidate_id": row["id"], "name": row["name"], "ranks": [], "win_rates": []} for row in candidates}
        for run_id in completed_run_ids:
            rows = per_run[run_id][label]
            if not any(row["wins"] + row["losses"] for row in rows):
                continue
            for rank, row in enumerate(rows, 1):
                metrics[row["candidate_id"]]["ranks"].append(rank)
                if row["win_percentage"] is not None:
                    metrics[row["candidate_id"]]["win_rates"].append(row["win_percentage"])
        consensus[label] = sorted([
            {"candidate_id": item["candidate_id"], "name": item["name"], "models_included": len(item["ranks"]),
             "average_rank": round(sum(item["ranks"]) / len(item["ranks"]), 2) if item["ranks"] else None,
             "rank_range": max(item["ranks"]) - min(item["ranks"]) if item["ranks"] else None,
             "worst_rank": max(item["ranks"]) if item["ranks"] else None,
             "average_win_rate": round(sum(item["win_rates"]) / len(item["win_rates"]), 1) if item["win_rates"] else None,
             "lowest_win_rate": min(item["win_rates"]) if item["win_rates"] else None}
            for item in metrics.values()
        ], key=lambda item: (item["average_rank"] is None, item["average_rank"] or 999, -(item["average_win_rate"] or -1), item["name"]))
    bias: dict[str, dict[str, Any]] = {row["id"]: {"candidate_id": row["id"], "name": row["name"], "a_wins": 0, "a_total": 0, "b_wins": 0, "b_total": 0} for row in candidates}
    for row in attempts:
        if row["parsed_choice"] == "invalid":
            continue
        a, b, winner = str(row["candidate_a_id"]), str(row["candidate_b_id"]), str(row["selected_candidate_id"])
        bias[a]["a_total"] += 1; bias[b]["b_total"] += 1
        if winner == a: bias[a]["a_wins"] += 1
        if winner == b: bias[b]["b_wins"] += 1
    position_bias = []
    for item in bias.values():
        a_rate = round(100 * item["a_wins"] / item["a_total"], 1) if item["a_total"] else None
        b_rate = round(100 * item["b_wins"] / item["b_total"], 1) if item["b_total"] else None
        position_bias.append({**item, "a_win_rate": a_rate, "b_win_rate": b_rate, "difference": round(a_rate - b_rate, 1) if a_rate is not None and b_rate is not None else None})
    complete_runs = [run for run in experiment["runs"] if str(run["id"]) in completed_run_ids]
    model_winners = {
        str(run["label"]): {label: per_run[str(run["id"])][label][0]["name"] for label in labels if per_run[str(run["id"])][label]}
        for run in complete_runs
    }
    consensus_winners = {label: rows[0]["name"] for label, rows in consensus.items() if rows and rows[0]["models_included"] == len(complete_runs)}
    complete = len(complete_runs) == 3 and all(len([row for row in attempts if row["run_id"] == run["id"] and row["parsed_choice"] != "invalid"]) == 40 for run in complete_runs)
    report: dict[str, Any] = {"ready": complete, "model_winners": model_winners, "intent_consensus": consensus_winners}
    if complete:
        overall: dict[str, list[float]] = defaultdict(list)
        for rows in consensus.values():
            for row in rows:
                if row["average_rank"] is not None:
                    overall[str(row["name"])].append(float(row["average_rank"]))
        unified_name, unified_ranks = min(overall.items(), key=lambda item: (sum(item[1]) / len(item[1]), item[0]))
        consensus_count = sum(name == unified_name for name in consensus_winners.values())
        if consensus_count == len(labels): conclusion = "Clear unified winner"
        elif consensus_count >= 3: conclusion = "Best consensus winner, but not dominant"
        else: conclusion = "Evidence favors separate names for separate system functions"
        report.update({
            "conclusion": conclusion, "unified_candidate": unified_name,
            "unified_average_rank": round(sum(unified_ranks) / len(unified_ranks), 2),
            "specialization_detected": len(set(consensus_winners.values())) > 1,
            "polarizing_names": [row["name"] for rows in consensus.values() for row in rows if (row["rank_range"] or 0) >= 3],
            "position_bias_flags": [row["name"] for row in position_bias if row["difference"] is not None and abs(float(row["difference"])) >= 20],
        })
    return {"labels": labels, "per_run": per_run, "consensus": consensus, "position_bias": position_bias, "report": report}

def _reversal_validation_analysis(experiment: dict[str, Any], attempts: list[dict[str, Any]], candidates: list[dict[str, Any]]) -> dict[str, Any]:
    snapshot = json.loads(str(experiment["configuration_snapshot"]))
    if snapshot.get("kind") != "intent_class_reversal_v1":
        return {}
    labels = [str(item["label"]) for item in snapshot["intent_classes"]]
    scenario_labels = {str(item["scenario_id"]): str(item["label"]) for item in snapshot["intent_classes"]}
    per_run: dict[str, dict[str, list[dict[str, Any]]]] = {}; classifications: dict[str, dict[str, dict[str, int]]] = {}; side_bias: dict[str, dict[str, Any]] = {}
    completed_run_ids = {str(run["id"]) for run in experiment["runs"] if run["status"] == "completed"}
    for run in experiment["runs"]:
        run_id = str(run["id"]); run_attempts = [row for row in attempts if row["run_id"] == run_id]
        side_bias[run_id] = {"label": run["label"], "a_selections": sum(row["parsed_choice"] == "A" for row in run_attempts), "b_selections": sum(row["parsed_choice"] == "B" for row in run_attempts), "total": len(run_attempts)}
        per_run[run_id] = {}; classifications[run_id] = {}
        for label in labels:
            grouped: dict[tuple[str, str, str], list[dict[str, Any]]] = defaultdict(list)
            for row in run_attempts:
                if scenario_labels.get(str(row["scenario_id"])) == label:
                    grouped[(str(row["scenario_id"]), *sorted((str(row["candidate_a_id"]), str(row["candidate_b_id"]))))].append(row)
            metric = {item["id"]: {"candidate_id": item["id"], "name": item["name"], "robust_wins": 0, "robust_losses": 0, "position_sensitive_splits": 0, "other": 0, "total_logical_comparisons": 0} for item in candidates}
            summary = {"robust": 0, "a_side_sensitive": 0, "b_side_sensitive": 0, "other": 0, "total": len(grouped)}
            for (_, left, right), rows in grouped.items():
                metric[left]["total_logical_comparisons"] += 1; metric[right]["total_logical_comparisons"] += 1
                if len(rows) != 2 or any(row["parsed_choice"] == "invalid" for row in rows):
                    metric[left]["other"] += 1; metric[right]["other"] += 1; summary["other"] += 1; continue
                winners = [str(row["selected_candidate_id"]) for row in rows]
                if winners[0] == winners[1]:
                    winner, loser = winners[0], right if winners[0] == left else left
                    metric[winner]["robust_wins"] += 1; metric[loser]["robust_losses"] += 1; summary["robust"] += 1
                elif all(str(row["selected_candidate_id"]) == str(row["candidate_a_id"]) for row in rows):
                    metric[left]["position_sensitive_splits"] += 1; metric[right]["position_sensitive_splits"] += 1; summary["a_side_sensitive"] += 1
                elif all(str(row["selected_candidate_id"]) == str(row["candidate_b_id"]) for row in rows):
                    metric[left]["position_sensitive_splits"] += 1; metric[right]["position_sensitive_splits"] += 1; summary["b_side_sensitive"] += 1
                else:
                    metric[left]["other"] += 1; metric[right]["other"] += 1; summary["other"] += 1
            rows = []
            for item in metric.values():
                resolved = item["robust_wins"] + item["robust_losses"]
                item["robust_win_rate"] = round(100 * item["robust_wins"] / resolved, 1) if resolved else None
                item["position_sensitive_share"] = round(100 * item["position_sensitive_splits"] / item["total_logical_comparisons"], 1) if item["total_logical_comparisons"] else None
                item["effective_score"] = round(item["robust_wins"] + 0.5 * item["position_sensitive_splits"], 2)
                rows.append(item)
            per_run[run_id][label] = sorted(rows, key=lambda item: (-item["effective_score"], -item["robust_wins"], item["name"]))
            classifications[run_id][label] = summary
    consensus: dict[str, list[dict[str, Any]]] = {}
    for label in labels:
        metrics = {item["id"]: {"candidate_id": item["id"], "name": item["name"], "ranks": [], "robust_rates": [], "split_shares": []} for item in candidates}
        for run_id in completed_run_ids:
            for rank, row in enumerate(per_run[run_id][label], 1):
                metrics[row["candidate_id"]]["ranks"].append(rank)
                if row["robust_win_rate"] is not None: metrics[row["candidate_id"]]["robust_rates"].append(row["robust_win_rate"])
                if row["position_sensitive_share"] is not None: metrics[row["candidate_id"]]["split_shares"].append(row["position_sensitive_share"])
        consensus[label] = sorted([{"candidate_id": item["candidate_id"], "name": item["name"], "models_included": len(item["ranks"]), "average_rank": round(sum(item["ranks"]) / len(item["ranks"]), 2) if item["ranks"] else None, "worst_rank": max(item["ranks"]) if item["ranks"] else None, "average_robust_win_rate": round(sum(item["robust_rates"]) / len(item["robust_rates"]), 1) if item["robust_rates"] else None, "average_position_sensitive_share": round(sum(item["split_shares"]) / len(item["split_shares"]), 1) if item["split_shares"] else None} for item in metrics.values()], key=lambda item: (item["average_rank"] is None, item["average_rank"] or 999, -(item["average_robust_win_rate"] or -1), item["name"]))
    complete_runs = [run for run in experiment["runs"] if str(run["id"]) in completed_run_ids]
    complete = len(complete_runs) == 3 and all(len([row for row in attempts if row["run_id"] == run["id"] and row["parsed_choice"] != "invalid"]) == 80 for run in complete_runs)
    report: dict[str, Any] = {"ready": complete, "intent_consensus": {label: rows[0]["name"] for label, rows in consensus.items() if rows}}
    if complete:
        winners = report["intent_consensus"]
        architecture = winners.get("Retrieval") == "Agent Research Commons" and winners.get("Contribution") == "Interagent Research Commons" and winners.get("Collaboration") == "Interagent Research Commons" and winners.get("Autonomy") == "Agent Commons"
        report["conclusion"] = "Architecture validated" if architecture else "Architecture mostly validated with one layer changed" if len(set(winners.values())) > 1 else "Single umbrella name preferable"
        report["architecture_validated"] = architecture
    return {"labels": labels, "per_run": per_run, "classifications": classifications, "consensus": consensus, "side_bias": side_bias, "report": report}

def analyze(data):
    output = {}
    for item in data['experiments']:
        trials = {t['id']:t for t in item['trials']}
        runs = {r['id']:r for r in item['runs']}
        attempts = [{**trials[a['trial_id']], **a, 'label': runs[a['run_id']]['label']} for a in item['outcomes']]
        experiment = {**item, 'configuration_snapshot':json.dumps(item['configuration_snapshot'])}
        function = _intent_class_analysis if item['configuration_snapshot']['kind']=='intent_class_final_v1' else _reversal_validation_analysis
        output[item['configuration_snapshot']['kind']] = function(experiment, attempts, item['candidates'])
    return output

if __name__ == '__main__':
    source = Path(sys.argv[1]) if len(sys.argv)>1 else Path(__file__).with_name('trials.json')
    print(json.dumps(analyze(json.loads(source.read_text())), indent=2, sort_keys=True))
