"""Ingest Knowledge Base documents (Project Knowledge + Legal Documents) into Qdrant Vector Store."""

from __future__ import annotations

from pathlib import Path

from app.services.knowledge_base_service import KnowledgeBaseService

from app.api.dependencies import get_orchestrator

KNOWLEDGE_ROOT = Path(__file__).resolve().parents[1] / "KNOWLEDGE_BASE"


def chunk_markdown(text: str, max_chars: int = 800) -> list[str]:
    paragraphs = text.split("\n\n")
    chunks = []
    current = ""
    for p in paragraphs:
        p_clean = p.strip()
        if not p_clean:
            continue
        if len(current) + len(p_clean) > max_chars:
            if current:
                chunks.append(current.strip())
            current = p_clean
        else:
            current = f"{current}\n\n{p_clean}" if current else p_clean
    if current:
        chunks.append(current.strip())
    return chunks


def ingest_all_knowledge():
    print(f"Scanning KNOWLEDGE_BASE at: {KNOWLEDGE_ROOT}")
    service = KnowledgeBaseService()
    orchestrator = get_orchestrator()

    md_files = list(KNOWLEDGE_ROOT.glob("**/*.md"))
    print(f"Found {len(md_files)} markdown legal / project documents.")

    total_chunks = 0
    for doc_path in md_files:
        content = doc_path.read_text(encoding="utf-8")
        chunks = chunk_markdown(content)
        rel_path = doc_path.relative_to(KNOWLEDGE_ROOT)
        category = rel_path.parts[0] if len(rel_path.parts) > 1 else "GENERAL"

        print(f"-> Ingesting [{category}] {doc_path.name}: {len(chunks)} chunks")
        for idx, chunk in enumerate(chunks):
            # Ingest through knowledge orchestrator into Qdrant dscons_knowledge collection
            doc_id = f"KB_{doc_path.stem}_{idx}"
            payload = {
                "document_id": doc_id,
                "title": doc_path.stem.replace("_", " "),
                "category": category,
                "file_path": str(doc_path),
                "relative_path": str(rel_path),
                "chunk_index": idx,
                "text": chunk,
            }
            orchestrator.add_document_chunk(
                doc_id=doc_id,
                text=chunk,
                metadata=payload,
            )
            total_chunks += 1

    print(
        f"\n Successfully indexed {total_chunks} knowledge chunks into Qdrant Vector Store!"
    )


if __name__ == "__main__":
    ingest_all_knowledge()
