#!/usr/bin/env python3
"""
Generates the study/source membership map from the unified database.
This is a traceability aid for provenance-aware discussion.
"""
from __future__ import annotations
from pathlib import Path
import pandas as pd

ROOT = Path(__file__).resolve().parents[1]
CURATED = ROOT / "data_curated"
RESULTS = ROOT / "results"
RESULTS.mkdir(exist_ok=True)

def normalize_author(author: str) -> str:
    return str(author).strip().lower()

def main() -> None:
    df = pd.read_csv(CURATED / "base_unificada_curada.csv")
    df["study_key"] = df["author"].map(normalize_author)
    usage_sets = df.groupby(["study_id","study_key","author"])["usage_group"].agg(lambda s: "|".join(sorted(set(map(str, s))))).reset_index()
    usage_sets.rename(columns={"usage_group":"usage_membership"}, inplace=True)
    usage_sets.to_csv(RESULTS / "study_membership_map.csv", index=False)
    print(usage_sets.to_string(index=False))

if __name__ == "__main__":
    main()
