from __future__ import annotations

from pathlib import Path
from typing import List

import bibtexparser
from bibtexparser.bparser import BibTexParser
from bibtexparser.bwriter import BibTexWriter

from ..types import ReferenceInput
from ..util import stable_hash


def _split_authors(author_field: str) -> list[str]:
    if not author_field:
        return []
    parts = [part.strip() for part in author_field.replace("\n", " ").split(" and ")]
    return [p for p in parts if p]


def ingest_bibtex(path: str) -> List[ReferenceInput]:
    content = Path(path).read_text(encoding="utf-8")
    parser = BibTexParser(common_strings=True)
    bib_db = bibtexparser.loads(content, parser=parser)
    writer = BibTexWriter()
    writer.indent = "  "
    writer.order_entries_by = None

    refs: List[ReferenceInput] = []
    for entry in bib_db.entries:
        entry_type = entry.get("ENTRYTYPE", "misc")
        entry_id = entry.get("ID") or ""
        db = bibtexparser.bibdatabase.BibDatabase()
        db.entries = [entry]
        raw = writer.write(db).strip()

        fields = {
            "entry_type": entry_type,
            "title": entry.get("title"),
            "author": entry.get("author"),
            "authors": _split_authors(entry.get("author", "")),
            "year": entry.get("year"),
            "doi": entry.get("doi"),
            "eprint": entry.get("eprint"),
            "archivePrefix": entry.get("archivePrefix") or entry.get("archiveprefix"),
            "isbn": entry.get("isbn"),
            "journal": entry.get("journal"),
            "booktitle": entry.get("booktitle"),
            "publisher": entry.get("publisher"),
            "url": entry.get("url"),
        }
        fields = {k: v for k, v in fields.items() if v}
        ref = ReferenceInput(
            source_path=path,
            source_kind="bibtex",
            ref_id=entry_id or f"ref_{stable_hash(raw)}",
            raw=raw,
            fields=fields,
            parse_confidence="HIGH",
        )
        refs.append(ref)
    return refs
