#!/usr/bin/env python3
"""Merge per-developer all.json files into one aggregated all.json."""

import json
from pathlib import Path
from collections import Counter

BASE = Path("/home/sagar/trace/analysis-14022026/analyzers/output")
OUT_DIR = Path("/home/sagar/trace/analysis-14022026/dashboard-v2/public/data")
PERIOD = "2026-01-01_to_2026-02-28"

USERS = {
    "54902986+zzjjaayy_at_users_noreply_github_com": "zzjjaayy",
    "ajaysingh07032003_at_gmail_com": "ajay",
    "patil_vaibhav2147_vp_at_gmail_com": "vaibhav",
}

user_data = {}
for folder, short in USERS.items():
    p = BASE / folder / PERIOD / "all.json"
    with open(p) as f:
        user_data[short] = json.load(f)

ANALYZER_KEYS = [f"a{i:02d}" for i in range(1, 11)]
# Get full key names
akey_full = {}
for ak in ANALYZER_KEYS:
    for k in user_data["zzjjaayy"]:
        if k.startswith(ak):
            akey_full[ak] = k
            break

merged = {}

for ak, full_key in akey_full.items():
    first = user_data["zzjjaayy"][full_key]
    summary_keys = [k for k in first if k != "per_session"]
    
    merged_analyzer = {}
    for sk in summary_keys:
        vals = [user_data[dev][full_key].get(sk, 0) for dev in user_data]
        if all(isinstance(v, (int, float)) for v in vals):
            merged_analyzer[sk] = sum(vals) if all(isinstance(v, int) for v in vals) else round(sum(vals), 4)
        else:
            merged_analyzer[sk] = vals[0]
    
    merged_sessions = []
    for dev, data in user_data.items():
        for sess in data[full_key].get("per_session", []):
            sess_copy = dict(sess)
            sess_copy["developer"] = dev
            merged_sessions.append(sess_copy)
    merged_analyzer["per_session"] = merged_sessions
    merged[full_key] = merged_analyzer

# c01_developer_profile
profiles = {dev: data["c01_developer_profile"]["profile"] for dev, data in user_data.items()}
total_sessions = sum(p["session_count"] for p in profiles.values())
total_cost = sum(p["total_cost_usd"] for p in profiles.values())

def wavg(field):
    return sum(profiles[d][field] * profiles[d]["session_count"] for d in profiles) / total_sessions

source_counts = Counter(p["preferred_source"] for p in profiles.values())
preferred = source_counts.most_common(1)[0][0]

merged["c01_developer_profile"] = {
    "total_sessions": total_sessions,
    "profile": {
        "session_count": total_sessions,
        "sessions_per_active_day": round(wavg("sessions_per_active_day"), 2),
        "preferred_source": preferred,
        "avg_prompts_per_session": round(wavg("avg_prompts_per_session"), 2),
        "avg_first_prompt_length": round(wavg("avg_first_prompt_length"), 1),
        "interrupt_rate": round(wavg("interrupt_rate"), 4),
        "undo_rate": round(wavg("undo_rate"), 4),
        "edit_session_pct": round(wavg("edit_session_pct"), 4),
        "commit_session_pct": round(wavg("commit_session_pct"), 4),
        "avg_autonomy_ratio": round(wavg("avg_autonomy_ratio"), 2),
        "exploration_tendency": round(wavg("exploration_tendency"), 2),
        "total_cost_usd": round(total_cost, 2),
    },
    "per_developer": {dev: prof for dev, prof in profiles.items()},
}

# c02_team_trends
all_weeks = {}
per_dev_weeks = []

for dev, data in user_data.items():
    for w in data["c02_team_trends"]["weeks"]:
        iw = w["iso_week"]
        if iw not in all_weeks:
            all_weeks[iw] = []
        all_weeks[iw].append((dev, w))
        per_dev_weeks.append({**w, "developer": dev})

merged_weeks = []
for iw, entries in sorted(all_weeks.items()):
    total_sess = sum(e[1]["sessions_count"] for e in entries)
    total_cost_w = sum(e[1]["total_cost"] for e in entries)
    edit_pct = sum(e[1]["edit_sessions_pct"] * e[1]["sessions_count"] for e in entries) / total_sess
    int_rate = sum(e[1]["interrupt_rate"] * e[1]["sessions_count"] for e in entries) / total_sess
    src_dist = Counter()
    for _, w in entries:
        for src, cnt in w.get("source_distribution", {}).items():
            src_dist[src] += cnt
    merged_weeks.append({
        "iso_week": iw,
        "sessions_count": total_sess,
        "edit_sessions_pct": round(edit_pct, 4),
        "interrupt_rate": round(int_rate, 4),
        "avg_session_cost": round(total_cost_w / total_sess, 4),
        "total_cost": round(total_cost_w, 2),
        "source_distribution": dict(src_dist),
    })

merged["c02_team_trends"] = {
    "total_sessions": total_sessions,
    "weeks": merged_weeks + per_dev_weeks,
}

OUT_DIR.mkdir(parents=True, exist_ok=True)
with open(OUT_DIR / "all.json", "w") as f:
    json.dump(merged, f, indent=2)
with open(OUT_DIR / "developers.json", "w") as f:
    json.dump(list(USERS.values()), f, indent=2)

print(f"Written: {OUT_DIR / 'all.json'}")
print(f"Written: {OUT_DIR / 'developers.json'}")
print(f"\nTotal sessions: {total_sessions}")
print(f"Total cost: ${total_cost:.2f}")
print(f"Developers: {list(USERS.values())}")
for ak, full_key in akey_full.items():
    n = len(merged[full_key]["per_session"])
    print(f"  {full_key}: {n} session records")
print(f"  c01: merged profile across {len(profiles)} developers")
print(f"  c02: {len(merged_weeks)} merged weeks, {len(per_dev_weeks)} per-dev week entries")
