"""Document / resume / JD parsing with real text extraction."""

from __future__ import annotations

from app.schemas.common import JobStatus
from app.schemas.documents import (
    DocumentParseRequest,
    DocumentParseResponse,
    ParseTarget,
    ParsedBlock,
)
from app.services.shared.ai_generate import generate_json
from app.services.screening.document_extract import (
    enrich_structured,
    extract_text,
    load_document_bytes,
    looks_like_resume,
    structure_job_description,
    structure_resume,
    text_to_blocks,
)


class DocumentsService:
    async def parse(self, payload: DocumentParseRequest) -> DocumentParseResponse:
        data_bytes = await load_document_bytes(
            content_base64=payload.content_base64,
            source_url=payload.source_url,
        )
        raw_text = extract_text(data_bytes, payload.document_type)
        source_hint = payload.source_url or payload.filename or "document"

        # Resume-like uploads with parse_target=raw_text still get structured fields.
        effective_target = payload.parse_target
        if (
            effective_target == ParseTarget.RAW_TEXT
            and raw_text
            and looks_like_resume(raw_text)
        ):
            effective_target = ParseTarget.RESUME

        system = (
            "You extract structured data from documents. "
            "Return JSON only with keys: "
            "raw_text (string), "
            "blocks (array of {block_id, block_type, text, page}), "
            "structured (object). "
            "For parse_target=resume, structured MUST include non-empty "
            "name, email, phone, skills[], experience[], education[], summary. "
            "For parse_target=job_description, structured must include "
            "title, responsibilities[], requirements[], skills[]. "
            "Never return an empty structured object when text is available."
        )
        user = (
            f"parse_target={effective_target.value}\n"
            f"document_type={payload.document_type.value}\n"
            f"language={payload.language}\n"
            f"source={source_hint}\n"
            f"extracted_text:\n{raw_text[:12000] or '(empty — image/binary without text layer)'}"
        )

        def local() -> dict:
            if effective_target == ParseTarget.RESUME:
                structured = structure_resume(raw_text)
            elif effective_target == ParseTarget.JOB_DESCRIPTION:
                structured = structure_job_description(raw_text)
            elif payload.parse_target == ParseTarget.RAW_TEXT:
                structured = {"char_count": len(raw_text)}
            else:
                structured = {"note": f"local parse for {payload.parse_target.value}"}
            return {
                "raw_text": raw_text or None,
                "blocks": text_to_blocks(raw_text),
                "structured": structured,
            }

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )

        resolved_text = data.get("raw_text") or raw_text or None
        text_for_struct = resolved_text or raw_text or ""

        structured = enrich_structured(
            data.get("structured") if isinstance(data.get("structured"), dict) else {},
            raw_text=text_for_struct,
            parse_target=effective_target.value,
        )

        blocks_raw = data.get("blocks") or text_to_blocks(text_for_struct)
        blocks = [
            ParsedBlock(
                block_id=str(b.get("block_id", f"b-{i}")),
                block_type=str(b.get("block_type", "paragraph")),
                text=str(b.get("text", "")),
                page=b.get("page"),
                metadata=b.get("metadata") or {},
            )
            for i, b in enumerate(blocks_raw)
            if isinstance(b, dict)
        ]
        if not blocks and text_for_struct:
            blocks = [
                ParsedBlock(**b) for b in text_to_blocks(text_for_struct)
            ]

        return DocumentParseResponse(
            correlation_id=payload.correlation_id,
            document_type=payload.document_type,
            parse_target=payload.parse_target,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Parsed document via {provider}",
            raw_text=resolved_text,
            blocks=blocks,
            structured=structured,
        )
