#!/usr/bin/env python3
"""Reproduce the 2026 AI Coding Stack Map from Stack Overflow's public CSV.

Download survey_results_public.csv from the 2026 Stack Overflow Survey
archive, then run: python3 reproduce.py survey_results_public.csv
Outputs: data.json and pair-overlap.csv in the working directory.

Source: 2026 Stack Overflow Developer Survey (ODbL 1.0).
https://github.com/StackExchange/Survey/tree/main/packages/archive/2026
"""
import argparse
import csv
import hashlib
import json
from collections import Counter
from itertools import combinations
from pathlib import Path

FIELD = "AICodeAgentHaveWorkedWith"
SOURCE = "https://survey.stackoverflow.co/2026/ai/data/ai-code-agent"


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("survey_csv", type=Path)
    parser.add_argument("--json", type=Path, default=Path("data.json"))
    parser.add_argument("--csv", type=Path, default=Path("pair-overlap.csv"))
    args = parser.parse_args()

    with args.survey_csv.open("rb") as source:
        checksum = hashlib.file_digest(source, "sha256").hexdigest()

    tools = Counter()
    overlap = Counter()
    selections = Counter()
    rows = 0
    with args.survey_csv.open(encoding="utf-8-sig", newline="") as source:
        reader = csv.DictReader(source)
        if FIELD not in (reader.fieldnames or []):
            parser.error(f"Input CSV is missing {FIELD}")
        for row in reader:
            rows += 1
            names = {name.strip() for name in row[FIELD].split(";")} - {"", "NA"}
            if not names:
                continue
            selections[len(names)] += 1
            tools.update(names)
            overlap.update(combinations(sorted(names), 2))

    eligible = sum(selections.values())
    if len(tools) < 8:
        parser.error("Input CSV does not contain at least eight named tools")

    top = sorted(tools, key=lambda name: (-tools[name], name))[:8]
    tool_data = [
        {"id": name.lower().replace(" ", "-"), "name": name, "count": tools[name]}
        for name in top
    ]
    pairs = sorted(
        (
            {"tools": [left["id"], right["id"]],
             "count": overlap[tuple(sorted((left["name"], right["name"])))]}
            for left, right in combinations(tool_data, 2)
        ),
        key=lambda pair: (-pair["count"], pair["tools"]),
    )
    data = {
        "source": SOURCE,
        "sha256": checksum,
        "rows": rows,
        "eligible": eligible,
        "multiple": eligible - selections[1],
        "tools": tool_data,
        "pairs": pairs,
    }
    args.json.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")

    by_id = {tool["id"]: tool for tool in tool_data}
    with args.csv.open("w", encoding="utf-8", newline="") as output:
        writer = csv.writer(output, lineterminator="\n")
        writer.writerow([
            "tool_a", "tool_b", "respondents_selecting_both", "eligible_respondents",
            "tool_a_respondents", "tool_b_respondents", "percent_of_eligible",
            "percent_of_tool_a", "percent_of_tool_b", "source", "source_license",
        ])
        for pair in pairs:
            left, right = (by_id[tool_id] for tool_id in pair["tools"])
            count = pair["count"]
            writer.writerow([
                left["name"], right["name"], count, eligible, left["count"], right["count"],
                f"{100 * count / eligible:.6f}", f"{100 * count / left['count']:.6f}",
                f"{100 * count / right['count']:.6f}", SOURCE, "ODbL-1.0",
            ])


if __name__ == "__main__":
    main()
