"""J Autoimmun 2024, doi 10.1016/j.jaut.2024.103327 (GSE281263): primary biliary cholangitis, PDC-E2 peptide stimulation (activation-induced marker assay), single-cell MiXCR table
(Smart-seq style, one row per chain). CD154+CD69+ CD4 Tconv and CD127loCD25+ CD4 Treg, 3 healthy donors and 1 PBC patient. Cells are identified by `libid` (595 cells, one donor and one CD4Type each),
NOT by `sample_name`: `sample_name` (e.g. A10_HC_subject4_PDC-E2) is a plate position plus subject and is shared by a Tconv and a Treg cell of the same donor (483 names for 595 cells).
Only TRA and TRB rows are used (TRG/TRD dropped). A cell with two alpha or two beta chains gives one record per alpha/beta combination (`cells` counts combinations).
`expanded` (meaning not documented) is not used. HLA-DRB1 types are the donor types (all `DRB1*0401` for healthy donors, `DRB1*0402` for the patient), put in `context`, not a mapped restriction.
Antigen "PDC-E2 peptides" (peptide pool as printed in `stimulation`); no epitope is given per TCR in the table. The Treg sort label is kept as printed in `context`."""
import pandas as pd
from atlas import SRC, clones


def parse():
    t = pd.read_csv(SRC / "Tewari2024/GSE281263_P461_tcrs.txt.gz", sep="\t", low_memory=False)
    t = t[t.chain.isin(["TRA", "TRB"])]
    meta = t.drop_duplicates("libid").set_index("libid")[["donorID", "studyGroup", "CD4Type", "sort", "hla"]]
    ch = lambda c, n: t[t.chain == c].rename(columns={"v_gene": f"TRV{n}", "j_gene": f"TRJ{n}", "junction": f"CDR3{n.lower()}"})
    t["v_gene"] = t.v_gene.str.replace(r"(?<=\d)DV", "/DV", regex=True)  # TRAV29DV5 -> TRAV29/DV5, the atlas convention
    a = ch("TRA", "A")[["libid", "TRVA", "TRJA", "CDR3a"]].rename(columns={"TRVA": "TRAV", "TRJA": "TRAJ"})
    b = ch("TRB", "B")[["libid", "TRVB", "TRJB", "CDR3b"]].rename(columns={"TRVB": "TRBV", "TRJB": "TRBJ"})
    d = a.merge(b, on="libid", how="outer").join(meta, on="libid")
    d["donor"] = d.donorID
    d["context"] = ("primary biliary cholangitis study, " + d.studyGroup.map({"HC": "healthy donor", "PBC": "PBC patient"}) + ", " + d.CD4Type
                    + " (" + d["sort"].str.strip() + "), donor HLA " + d.hla)
    d["specificity_evidence"] = d.CD4Type.map({"Tconv": "CD154+CD69+ after PDC-E2 peptide stimulation (activation-induced marker assay)",
                                               "Treg": "CD127loCD25+ Treg after PDC-E2 peptide stimulation (activation-induced marker assay)"})
    return clones(d, ["donor", "context", "specificity_evidence"]).assign(
        source="Tewari 2024 (J Autoimmun)", study="doi:10.1016/j.jaut.2024.103327", species="human", cd4_evidence="sorted CD4+", antigen="PDC-E2 peptides",
        organism="Homo sapiens (autoantigen)", annotation_level="antigen")
