"""Nat Med 2019, doi 10.1038/s41591-019-0522-3 (GSE123813): basal cell carcinoma biopsies, CD45+CD3+ sorted T cells, 10x, before (pre) and after (post)
anti-PD-1. Only cells in the clusters Th17, Tregs and Tfh (CD4 clusters per the manifest; 'Naive' mixes CD4 and CD8 and all CD8_* clusters are left out).
SCC files are not loaded (their clusters are not checked here). TCR string `TRA:...;TRB:...`, no V or J genes in the file. Cells with more than one beta
chain are dropped (ambiguous); cells with one beta and one alpha are paired, cells with one beta and no alpha are beta-only records; cells with
two or more alpha chains are dropped. Donor = `patient`. No antigen specificity."""
import pandas as pd
from atlas import SRC, clones


def parse():
    m = pd.read_csv(SRC / "Yost2019/GSE123813_bcc_tcell_metadata.txt.gz", sep="\t")
    m = m[m.cluster.isin(["Th17", "Tregs", "Tfh"])]
    t = pd.read_csv(SRC / "Yost2019/GSE123813_bcc_tcr.txt.gz", sep="\t")
    d = m.merge(t, left_on="cell.id", right_index=True)
    a, b = d.cdr3s_aa.str.findall(r"TRA:([A-Z]+)"), d.cdr3s_aa.str.findall(r"TRB:([A-Z]+)")
    d = d[(a.str.len() <= 1) & (b.str.len() == 1)].copy()
    d["CDR3a"], d["CDR3b"] = d.cdr3s_aa.str.extract(r"TRA:([A-Z]+)")[0], d.cdr3s_aa.str.extract(r"TRB:([A-Z]+)")[0]
    d["donor"] = d.patient
    d["context"] = "basal cell carcinoma, " + d.treatment + " anti-PD-1, " + d.cluster
    d = clones(d, ["donor", "context"])
    return d.assign(source="Yost 2019 (Nat Med)", study="GEO:GSE123813", species="human", cd4_evidence="CD4 cluster (single cell)", specificity_evidence="none", annotation_level="none")
