from __future__ import annotations

import re
from typing import List

import docx

from ..extract_ids import extract_ids
from ..types import ReferenceInput
from ..util import collapse_whitespace, stable_hash


SECTION_HEADERS = re.compile(r"^(references|bibliography|works cited)$", re.IGNORECASE)


def _is_heading(paragraph: docx.text.paragraph.Paragraph) -> bool:
    style_name = getattr(paragraph.style, "name", "") or ""
    if style_name.lower().startswith("heading"):
        return True
    text = paragraph.text.strip()
    return bool(SECTION_HEADERS.match(text))


def ingest_docx(path: str) -> List[ReferenceInput]:
    document = docx.Document(path)
    paragraphs = list(document.paragraphs)
    start_idx = None
    for idx, para in enumerate(paragraphs):
        if SECTION_HEADERS.match(para.text.strip()):
            start_idx = idx + 1
            break
    if start_idx is None:
        return []

    refs: List[ReferenceInput] = []
    for para in paragraphs[start_idx:]:
        if _is_heading(para) and para.text.strip():
            break
        text = collapse_whitespace(para.text)
        if not text:
            continue
        ids = extract_ids(text)
        fields = {"raw": text, **ids}
        refs.append(
            ReferenceInput(
                source_path=path,
                source_kind="docx",
                ref_id=f"ref_{stable_hash(text)}",
                raw=text,
                fields=fields,
                parse_confidence="LOW" if not ids else "MED",
            )
        )
    return refs
