"""引用导出引擎：BibTeX / RIS / EndNote / CSV / MLA"""





def _clean(s: str | None) -> str:
    return (s or "").replace("{", "").replace("}", "").replace("\\", "")


def _first_author(authors: list[dict]) -> str:
    if not authors:
        return "Unknown"
    a = authors[0]
    return f"{a.get('family', '')}, {a.get('given', '')}"


def _author_list(authors: list[dict], max_authors: int = 10) -> str:
    names = []
    for a in authors[:max_authors]:
        family = a.get("family", "")
        given = a.get("given", "")
        names.append(f"{family}, {given}")
    if len(authors) > max_authors:
        names.append("et al.")
    return " and ".join(names)


def _bibtex_key(lit: dict) -> str:
    author = lit.get("authors", [{"family": "Unknown"}])[0].get("family", "Unknown")
    year = lit.get("pub_year", "0000")
    title_words = lit.get("title", "article").split()[:2]
    key = f"{author.lower()}{year}{''.join(w[:4].capitalize() for w in title_words)}"
    return key.replace(" ", "").replace("-", "")


def format_bibtex(lit: dict) -> str:
    key = _bibtex_key(lit)
    author = _author_list(lit.get("authors", []))
    title = _clean(lit.get("title"))
    journal = _clean(lit.get("journal"))
    year = lit.get("pub_year", "")
    volume = lit.get("volume", "")
    pages = lit.get("pages", "")
    doi = lit.get("doi", "")
    pmid = lit.get("pmid", "")

    return f"""@article{{{key},
  author = {{{author}}},
  title = {{{title}}},
  journal = {{{journal}}},
  year = {{{year}}},
  volume = {{{volume}}},
  pages = {{{pages}}},
  doi = {{{doi}}},
  pmid = {{{pmid}}}
}}"""


def format_ris(lit: dict) -> str:
    lines = [
        "TY  - JOUR",
        f"TI  - {_clean(lit.get('title'))}",
        f"JO  - {_clean(lit.get('journal'))}",
        f"PY  - {lit.get('pub_year', '')}",
    ]
    if lit.get("volume"):
        lines.append(f"VL  - {lit.get('volume')}")
    if lit.get("issue"):
        lines.append(f"IS  - {lit.get('issue')}")
    if lit.get("pages"):
        lines.append(f"SP  - {lit.get('pages')}")
    if lit.get("doi"):
        lines.append(f"DO  - {lit.get('doi')}")
    for a in (lit.get("authors") or []):
        lines.append(f"AU  - {a.get('family', '')}, {a.get('given', '')}")
    lines.append(f"UR  - https://pubmed.ncbi.nlm.nih.gov/{lit.get('pmid', '')}/")
    lines.append("ER  - ")
    return "\n".join(lines)


def format_endnote(lit: dict) -> str:
    ref_type = "Journal Article"
    return f"""%0 {ref_type}
%T {_clean(lit.get('title'))}
%A {_author_list(lit.get('authors', []))}
%J {_clean(lit.get('journal'))}
%D {lit.get('pub_year', '')}
%V {lit.get('volume', '')}
%P {lit.get('pages', '')}
%@ {lit.get('doi', '')}
%U https://pubmed.ncbi.nlm.nih.gov/{lit.get('pmid', '')}/
%~ {lit.get('journal', '')}"""


def format_csv_header() -> str:
    return "Title,Authors,Journal,Year,Volume,Pages,DOI,PMID\n"


def format_csv_row(lit: dict) -> str:
    title = f'"{_clean(lit.get("title"))}"'
    authors = f'"{_author_list(lit.get("authors", []))}"'
    journal = f'"{_clean(lit.get("journal"))}"'
    return f"{title},{authors},{journal},{lit.get('pub_year', '')},{lit.get('volume', '')},{lit.get('pages', '')},{lit.get('doi', '')},{lit.get('pmid', '')}\n"


def format_mla(lit: dict) -> str:
    """MLA 9th Edition format.

    Author(s). "Title." Journal, vol. Volume, no. Issue, Year, pp. Pages. doi:DOI.
    """
    authors = lit.get("authors") or []
    if authors:
        first = authors[0]
        author_str = f"{first.get('family', '')}, {first.get('given', '')}"
        if len(authors) == 2:
            author_str += f", and {authors[1].get('family', '')} {authors[1].get('given', '')}"
        elif len(authors) > 2:
            author_str += ", et al."
    else:
        author_str = "Unknown Author"

    title = _clean(lit.get("title", ""))
    journal = _clean(lit.get("journal", ""))
    volume = lit.get("volume", "")
    issue = lit.get("issue", "")
    year = lit.get("pub_year", "")
    pages = lit.get("pages", "")
    doi = lit.get("doi", "")

    vol_issue = f"vol. {volume}" if volume else ""
    if issue:
        vol_issue += f", no. {issue}"
    pages_str = f", pp. {pages}" if pages else ""
    doi_str = f". doi:{doi}" if doi else "."

    parts = [f'{author_str}. "{title}."', journal]
    if vol_issue:
        parts.append(vol_issue)
    parts.append(str(year) + pages_str + doi_str)
    return " ".join(parts) + "\n"


EXPORTERS = {
    "bibtex": format_bibtex,
    "ris": format_ris,
    "endnote": format_endnote,
    "mla": format_mla,
}


def export_single(lit: dict, fmt: str) -> str:
    if fmt == "csv":
        return format_csv_header() + format_csv_row(lit)
    exporter = EXPORTERS.get(fmt)
    return exporter(lit) if exporter else ""


def export_batch(articles: list[dict], fmt: str) -> str:
    if fmt == "csv":
        lines = [format_csv_header()]
        for a in articles:
            lines.append(format_csv_row(a))
        return "".join(lines)
    exporter = EXPORTERS.get(fmt)
    if not exporter:
        return ""
    return "\n\n".join(exporter(a) for a in articles)
