"""Tests for Office document (docx/xlsx/pptx/pdf) ingestion into the graph.

Verifies that MarkItDown-supported binary formats are scanned, converted to
Markdown, and made searchable — not silently dropped.
"""
from __future__ import annotations

import os
from pathlib import Path

import pytest

from project_brain.build.builder import GraphBuilder
from project_brain.config import Config
from project_brain.graph.json_store import JsonStore
from project_brain.query.engine import QueryEngine
from project_brain.query.index import FileIndex, KeywordIndex, SymbolIndex


def _builder(project: Path):
    store = JsonStore(project / ".botbrain" / "graph")
    keyword = KeywordIndex()
    builder = GraphBuilder(
        project,
        Config.default(),
        store,
        keyword,
        SymbolIndex(),
        FileIndex(),
    )
    return builder, store, keyword


def _make_docx(path: Path, title: str, paragraphs: list[str]):
    """Create a minimal .docx file using python-docx."""
    import docx
    doc = docx.Document()
    doc.add_heading(title, level=1)
    for para in paragraphs:
        doc.add_paragraph(para)
    doc.save(str(path))


def _make_xlsx(path: Path, sheet_title: str, rows: list[list[str]]):
    """Create a minimal .xlsx file using openpyxl."""
    import openpyxl
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = sheet_title
    for row in rows:
        ws.append(row)
    wb.save(str(path))


# --------------------------------------------------------------------------
# docx
# --------------------------------------------------------------------------

class TestDocxIngestion:
    def test_docx_scanned_and_searchable(self, tmp_path):
        """A .docx file is scanned, converted to MD, and keyword-searchable."""
        project = tmp_path / "project"
        docs = project / "docs"
        docs.mkdir(parents=True)
        _make_docx(
            docs / "design.docx",
            "Payment Gateway Design",
            [
                "The payment gateway handles order checkout and refunds.",
                "process_payment is the core entry point for all transactions.",
            ],
        )

        builder, store, keyword = _builder(project)
        builder.build_all(persist=False)
        builder.rebuild_bm25_index(load_existing=False)
        builder.rebuild_symbol_file_indexes()

        # The docx should appear as a document node.
        docs_in_graph = [n for n in store.get_nodes_by_type("document")]
        assert any(n["path"] == "docs/design.docx" for n in docs_in_graph)

        # Searching for content from the docx should find it.
        engine = QueryEngine(store, keyword, builder.symbol_index, builder.file_index, project_path=str(project))
        results = engine.keyword_search("process_payment", top_k=10)
        assert len(results) >= 1
        # The hit should reference the docx file.
        assert any("design.docx" in (r.get("file") or "") for r in results)

    def test_docx_sections_created(self, tmp_path):
        """A .docx with headings produces section nodes."""
        project = tmp_path / "project"
        docs = project / "docs"
        docs.mkdir(parents=True)
        _make_docx(
            docs / "spec.docx",
            "API Specification",
            [
                "Overview of the API design.",
            ],
        )
        # Add a second heading via python-docx (add_heading creates sections)
        import docx
        doc = docx.Document(str(docs / "spec.docx"))
        doc.add_heading("Endpoints", level=2)
        doc.add_paragraph("GET /api/v1/users returns user list")
        doc.save(str(docs / "spec.docx"))

        builder, store, _ = _builder(project)
        builder.build_all(persist=False)

        sections = [n for n in store.get_nodes_by_type("section")]
        assert len(sections) >= 1


# --------------------------------------------------------------------------
# xlsx
# --------------------------------------------------------------------------

class TestXlsxIngestion:
    def test_xlsx_scanned_and_searchable(self, tmp_path):
        """A .xlsx file is scanned, converted to MD, and keyword-searchable."""
        project = tmp_path / "project"
        docs = project / "docs"
        docs.mkdir(parents=True)
        _make_xlsx(
            docs / "api_table.xlsx",
            "API Endpoints",
            [
                ["接口名称", "方法", "描述"],
                ["create_order", "POST", "创建订单"],
                ["query_order", "GET", "查询订单状态"],
            ],
        )

        builder, store, keyword = _builder(project)
        builder.build_all(persist=False)
        builder.rebuild_bm25_index(load_existing=False)
        builder.rebuild_symbol_file_indexes()

        docs_in_graph = [n for n in store.get_nodes_by_type("document")]
        assert any(n["path"] == "docs/api_table.xlsx" for n in docs_in_graph)

        engine = QueryEngine(store, keyword, builder.symbol_index, builder.file_index, project_path=str(project))
        results = engine.keyword_search("create_order", top_k=10)
        assert len(results) >= 1
        assert any("api_table.xlsx" in (r.get("file") or "") for r in results)

    def test_xlsx_table_content_in_markdown(self, tmp_path):
        """The xlsx is converted to a Markdown table (pipe-delimited)."""
        project = tmp_path / "project"
        docs = project / "docs"
        docs.mkdir(parents=True)
        _make_xlsx(
            docs / "config.xlsx",
            "Config",
            [["key", "value"], ["timeout", "30"]],
        )

        builder, store, _ = _builder(project)
        builder.build_all(persist=False)

        # The document node should have content (converted markdown).
        doc_nodes = [n for n in store.get_nodes_by_type("document") if n["path"] == "docs/config.xlsx"]
        assert doc_nodes
        # Check sections contain table-like content (pipe chars from MD table).
        sections = [n for n in store.get_nodes_by_type("section")
                     if n.get("doc_id") == doc_nodes[0]["id"]]
        all_section_text = " ".join(s.get("content", "") for s in sections)
        assert "timeout" in all_section_text or "timeout" in (doc_nodes[0].get("summary") or "")


# --------------------------------------------------------------------------
# Mixed: docx + xlsx + md coexist
# --------------------------------------------------------------------------

class TestMixedOfficeDocs:
    def test_mixed_office_and_markdown(self, tmp_path):
        """docx, xlsx, and md files all appear in the graph together."""
        project = tmp_path / "project"
        docs = project / "docs"
        docs.mkdir(parents=True)
        _make_docx(docs / "report.docx", "Report", ["Quarterly results summary."])
        _make_xlsx(docs / "data.xlsx", "Data", [["col1", "col2"], ["a", "b"]])
        (docs / "readme.md").write_text("# Readme\n\nProject readme.\n", encoding="utf-8")

        builder, store, _ = _builder(project)
        builder.build_all(persist=False)

        doc_paths = {n["path"] for n in store.get_nodes_by_type("document")}
        assert "docs/report.docx" in doc_paths
        assert "docs/data.xlsx" in doc_paths
        assert "docs/readme.md" in doc_paths