"""Ingest dual-write: vectors (existing) + structured FDI index."""

from __future__ import annotations

import hashlib
from pathlib import Path

from app.fdi.extract import extract_structured
from app.fdi.store import persist_structured
from app.saas import rag_debug as dbg


def index_document_structured(
    *,
    org_id: str,
    agent_id: str,
    kb_doc_id: str,
    path: Path,
    filename: str,
    mime_type: str | None = None,
) -> dict[str, object]:
    """Extract and persist structured financial knowledge for a KB document."""
    raw = path.read_bytes()
    sha = hashlib.sha256(raw).hexdigest()
    extract = extract_structured(path, filename)
    doc_id = persist_structured(
        org_id=org_id,
        agent_id=agent_id,
        kb_doc_id=kb_doc_id,
        filename=filename,
        storage_uri=str(path),
        sha256=sha,
        mime_type=mime_type,
        extract=extract,
    )
    dbg.log_info(
        "FDI indexed kb_doc=%s fdi_doc=%s type=%s conf=%.2f lines=%s ids=%s assertions=%s",
        kb_doc_id,
        doc_id,
        extract.doc_type,
        extract.doc_type_confidence,
        len(extract.lines),
        len(extract.identifiers),
        len(extract.assertions),
    )
    return {
        "fdi_document_id": doc_id,
        "doc_type": extract.doc_type,
        "doc_type_confidence": extract.doc_type_confidence,
        "parse_confidence": extract.parse_confidence,
        "line_count": len(extract.lines),
        "identifier_count": len(extract.identifiers),
        "assertion_count": len(extract.assertions),
        "warnings": list(extract.warnings),
    }
