"""Load document bytes and extract plain text (PDF / DOCX / text / HTML)."""

from __future__ import annotations

import base64
import io
import re
from email.utils import parseaddr
from html.parser import HTMLParser
from typing import Any

import httpx

from app.errors import GatewayError
from app.schemas.documents import DocumentType


class _HTMLTextExtractor(HTMLParser):
    def __init__(self) -> None:
        super().__init__()
        self._parts: list[str] = []
        self._skip = False

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        if tag in {"script", "style"}:
            self._skip = True
        elif tag in {"p", "br", "div", "li", "tr", "h1", "h2", "h3", "h4"}:
            self._parts.append("\n")

    def handle_endtag(self, tag: str) -> None:
        if tag in {"script", "style"}:
            self._skip = False

    def handle_data(self, data: str) -> None:
        if not self._skip and data.strip():
            self._parts.append(data)

    def text(self) -> str:
        return re.sub(r"\n{3,}", "\n\n", "".join(self._parts)).strip()


async def load_document_bytes(
    *,
    content_base64: str | None,
    source_url: str | None,
) -> bytes:
    if content_base64:
        try:
            return base64.b64decode(content_base64, validate=False)
        except Exception as exc:  # noqa: BLE001
            raise GatewayError(
                "Invalid content_base64",
                code="invalid_document",
                status_code=400,
            ) from exc

    if not source_url:
        raise GatewayError(
            "Provide content_base64 or source_url",
            code="invalid_document",
            status_code=400,
        )

    try:
        async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as client:
            res = await client.get(source_url)
            res.raise_for_status()
            return res.content
    except httpx.HTTPError as exc:
        raise GatewayError(
            f"Failed to fetch source_url: {exc}",
            code="document_fetch_failed",
            status_code=400,
        ) from exc


def extract_text(data: bytes, document_type: DocumentType) -> str:
    if not data:
        raise GatewayError(
            "Document bytes are empty",
            code="empty_document",
            status_code=400,
        )
    if document_type == DocumentType.PDF:
        return _extract_pdf(data)
    if document_type == DocumentType.DOCX:
        return _extract_docx(data)
    if document_type == DocumentType.DOC:
        return _extract_doc(data)
    if document_type in (DocumentType.HTML,):
        return _extract_html(data)
    if document_type == DocumentType.IMAGE:
        # No OCR in-gateway; caller / LLM must handle images separately.
        return ""
    # txt / markdown / unknown → utf-8 text
    return data.decode("utf-8", errors="replace").strip()


def _extract_doc(data: bytes) -> str:
    """Legacy .doc — only accept if the payload is actually a DOCX (PK zip)."""
    if data[:2] == b"PK":
        return _extract_docx(data)
    raise GatewayError(
        "Legacy .doc (OLE) is not supported. Convert to PDF or DOCX and retry.",
        code="unsupported_document_type",
        status_code=400,
        details={"document_type": "doc", "supported": ["pdf", "docx", "txt"]},
    )


def _extract_pdf(data: bytes) -> str:
    try:
        from pypdf import PdfReader
    except ImportError as exc:
        raise GatewayError(
            "PDF support requires pypdf",
            code="missing_dependency",
            status_code=500,
        ) from exc

    try:
        reader = PdfReader(io.BytesIO(data))
        pages = []
        for page in reader.pages:
            pages.append(page.extract_text() or "")
        return "\n".join(pages).strip()
    except Exception as exc:  # noqa: BLE001
        raise GatewayError(
            f"Failed to parse PDF: {exc}",
            code="document_parse_failed",
            status_code=400,
        ) from exc


def _extract_docx(data: bytes) -> str:
    try:
        from docx import Document
    except ImportError as exc:
        raise GatewayError(
            "DOCX support requires python-docx",
            code="missing_dependency",
            status_code=500,
        ) from exc

    try:
        doc = Document(io.BytesIO(data))
        parts = [p.text for p in doc.paragraphs if p.text and p.text.strip()]
        for table in doc.tables:
            for row in table.rows:
                cells = [c.text.strip() for c in row.cells if c.text and c.text.strip()]
                if cells:
                    parts.append(" | ".join(cells))
        return "\n".join(parts).strip()
    except Exception as exc:  # noqa: BLE001
        raise GatewayError(
            f"Failed to parse DOCX: {exc}",
            code="document_parse_failed",
            status_code=400,
        ) from exc


def _extract_html(data: bytes) -> str:
    html = data.decode("utf-8", errors="replace")
    parser = _HTMLTextExtractor()
    parser.feed(html)
    return parser.text()


_EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
_PHONE_RE = re.compile(
    r"\+?\d[\d\s\-()]{8,}\d"
)
# Canonical section key → accepted header phrases (lowercase)
_SECTION_ALIASES: dict[str, tuple[str, ...]] = {
    "summary": (
        "summary",
        "profile",
        "professional summary",
        "about me",
        "objective",
        "career objective",
    ),
    "skills": (
        "skills",
        "technical skills",
        "tech skills",
        "core skills",
        "key skills",
        "technologies",
    ),
    "experience": (
        "experience",
        "work experience",
        "employment",
        "professional experience",
        "work history",
        "employment history",
    ),
    "education": ("education", "academic background", "academics"),
    "projects": ("projects", "personal projects", "key projects"),
    "certifications": ("certifications", "certificates", "licenses"),
    "achievements": ("achievements", "awards", "accomplishments"),
}


def _canonical_section(header: str) -> str | None:
    key = header.lower().rstrip(":").strip()
    # Headers are short labels, not job titles / bullet lines.
    if not key or len(key) > 40 or len(key.split()) > 4:
        return None
    for canonical, aliases in _SECTION_ALIASES.items():
        if key in aliases:
            return canonical
    return None


def _split_sections(text: str) -> dict[str, str]:
    lines = text.splitlines()
    sections: dict[str, list[str]] = {"_preamble": []}
    current = "_preamble"
    for line in lines:
        stripped = line.strip()
        canonical = _canonical_section(stripped) if stripped else None
        if canonical:
            current = canonical
            sections.setdefault(current, [])
            continue
        sections.setdefault(current, []).append(line)
    return {k: "\n".join(v).strip() for k, v in sections.items() if v}


def looks_like_resume(text: str) -> bool:
    if not text or len(text.strip()) < 40:
        return False
    low = text.lower()
    has_contact = bool(_EMAIL_RE.search(text)) or "phone" in low
    markers = sum(
        1
        for m in (
            "experience",
            "education",
            "skills",
            "professional summary",
            "work experience",
            "technical skills",
        )
        if m in low
    )
    return has_contact and markers >= 2


def _skill_tokens(blob: str) -> list[str]:
    # Comma / pipe / bullet separated skills, plus known tech tokens
    candidates: list[str] = []
    for part in re.split(r"[,|/•\n;]+", blob):
        token = part.strip(" -\t")
        if 1 < len(token) <= 40 and not token.lower().startswith(
            ("and ", "with ", "including ")
        ):
            candidates.append(token)
    # Dedupe case-insensitively, keep first casing
    seen: set[str] = set()
    out: list[str] = []
    for c in candidates:
        low = c.lower()
        if low in seen:
            continue
        seen.add(low)
        out.append(c)
    return out[:40]


def structure_resume(text: str) -> dict[str, Any]:
    sections = _split_sections(text)
    emails = _EMAIL_RE.findall(text)
    phones = [
        re.sub(r"\s+", " ", p.strip())
        for p in _PHONE_RE.findall(text)
        if len(re.sub(r"\D", "", p)) >= 10
    ]
    preamble = sections.get("_preamble", "")
    name = None
    title = None
    for line in preamble.splitlines():
        line = line.strip()
        if not line or "@" in line or line.lower().startswith(("location:", "email:", "phone:", "http", "www")):
            continue
        if _PHONE_RE.fullmatch(line.replace(" ", "")):
            continue
        if name is None and len(line.split()) <= 6:
            name = line
            continue
        if name and title is None and ("|" in line or "developer" in line.lower() or "engineer" in line.lower()):
            title = line
            break

    skills_blob = sections.get("skills") or ""
    skills = _skill_tokens(skills_blob) if skills_blob else []

    exp_text = sections.get("experience") or ""
    experience = [
        {"raw": block.strip()}
        for block in re.split(r"\n{2,}", exp_text)
        if block.strip()
    ][:15]

    edu_text = sections.get("education") or ""
    education = [
        {"raw": block.strip()}
        for block in re.split(r"\n{2,}", edu_text)
        if block.strip()
    ][:10]

    summary = sections.get("summary") or None
    if not summary and preamble:
        # Prefer multi-line summary-like content after contact lines
        summary = preamble[:500] if len(preamble) > 20 else None

    email = emails[0] if emails else None
    if email:
        _, parsed = parseaddr(email)
        email = parsed or email

    location = None
    for line in text.splitlines():
        if line.strip().lower().startswith("location:"):
            location = line.split(":", 1)[-1].strip()
            break

    return {
        "name": name,
        "title": title,
        "email": email,
        "phone": phones[0] if phones else None,
        "location": location,
        "skills": skills,
        "experience": experience,
        "education": education,
        "summary": summary if isinstance(summary, str) else None,
        "sections": {k: v for k, v in sections.items() if k != "_preamble"},
    }


def enrich_structured(
    structured: dict[str, Any] | None,
    *,
    raw_text: str,
    parse_target: str,
) -> dict[str, Any]:
    """Fill missing structured fields from local extractors when LLM omits them."""
    current = dict(structured or {})
    target = (parse_target or "").lower()

    if target == "resume" or (target == "raw_text" and looks_like_resume(raw_text)):
        local = structure_resume(raw_text) if raw_text else {}
        if not current or current.keys() <= {"char_count", "note"}:
            return local
        for key, value in local.items():
            if key == "sections":
                if not current.get("sections"):
                    current["sections"] = value
                continue
            existing = current.get(key)
            empty = existing in (None, "", [], {})
            if empty and value not in (None, "", [], {}):
                current[key] = value
        return current

    if target == "job_description":
        local = structure_job_description(raw_text) if raw_text else {}
        if not current or current.keys() <= {"char_count", "note"}:
            return local
        for key, value in local.items():
            existing = current.get(key)
            empty = existing in (None, "", [], {})
            if empty and value not in (None, "", [], {}):
                current[key] = value
        return current

    return current


def structure_job_description(text: str) -> dict[str, Any]:
    sections = _split_sections(text)
    lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
    title = lines[0][:120] if lines else None

    req_keys = ("requirements", "qualifications", "must have", "required")
    resp_keys = ("responsibilities", "what you'll do", "duties", "role")

    requirements: list[str] = []
    responsibilities: list[str] = []
    for key, body in sections.items():
        low = key.lower()
        bullets = [
            ln.strip(" -•*\t")
            for ln in body.splitlines()
            if ln.strip() and (ln.strip().startswith(("-", "•", "*")) or len(ln.strip()) < 200)
        ]
        if any(k in low for k in req_keys):
            requirements.extend(bullets or [body[:500]])
        if any(k in low for k in resp_keys):
            responsibilities.extend(bullets or [body[:500]])

    if not requirements:
        requirements = [
            ln.strip(" -•*\t")
            for ln in text.splitlines()
            if ln.strip().startswith(("-", "•", "*"))
        ][:20]

    skills = _skill_tokens(
        "\n".join(requirements)
        or sections.get("skills", "")
        or text
    )
    # Prefer shorter skill-like tokens from common tech list if present in JD
    tech = [
        "Python",
        "Java",
        "JavaScript",
        "TypeScript",
        "React",
        "Node.js",
        "FastAPI",
        "Django",
        "SQL",
        "PostgreSQL",
        "MySQL",
        "MongoDB",
        "AWS",
        "GCP",
        "Azure",
        "Docker",
        "Kubernetes",
        "Redis",
        "GraphQL",
        "REST",
        "Go",
        "Rust",
        "C++",
        "Kotlin",
        "Swift",
    ]
    low_text = text.lower()
    found = [t for t in tech if t.lower() in low_text]
    for t in found:
        if t.lower() not in {s.lower() for s in skills}:
            skills.insert(0, t)
    skills = skills[:30]

    return {
        "title": title,
        "responsibilities": responsibilities[:25],
        "requirements": requirements[:25],
        "skills": skills,
        "sections": {k: v for k, v in sections.items() if k != "_preamble"},
    }


def text_to_blocks(text: str) -> list[dict[str, Any]]:
    paras = [p.strip() for p in re.split(r"\n{2,}", text) if p.strip()]
    if not paras and text.strip():
        paras = [text.strip()]
    return [
        {
            "block_id": f"b-{i + 1}",
            "block_type": "paragraph",
            "text": para[:4000],
            "page": 1,
        }
        for i, para in enumerate(paras[:40])
    ]
