"""Tests para vault_knowledge_parse."""

from __future__ import annotations

import os
import sqlite3
import sys
from pathlib import Path

import pytest

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from vault_knowledge_parse import vault_knowledge_parse


def _make_vault(tmp: Path) -> tuple[Path, Path]:
    """Crea un vault mínimo con vault_index.db."""
    db = tmp / "vault_index.db"
    conn = sqlite3.connect(str(db))
    conn.executescript(
        """
        CREATE TABLE IF NOT EXISTS files (
            rowid INTEGER PRIMARY KEY AUTOINCREMENT,
            rel_path TEXT UNIQUE NOT NULL,
            size_bytes INTEGER,
            ext TEXT
        );
        CREATE VIRTUAL TABLE IF NOT EXISTS files_fts
            USING fts5(rel_path, content_text, content='', contentless_delete=1);
        CREATE TABLE IF NOT EXISTS knowledge_docs (
            rel_path TEXT PRIMARY KEY,
            title TEXT,
            frontmatter_json TEXT,
            headings_json TEXT,
            parsed_at INTEGER
        );
        """
    )
    conn.commit()
    conn.close()
    return tmp, db


def _insert_file_entry(db: Path, rel_path: str):
    conn = sqlite3.connect(str(db))
    conn.execute(
        "INSERT OR IGNORE INTO files(rel_path, size_bytes, ext) VALUES (?, 0, '.md')",
        (rel_path,),
    )
    conn.commit()
    conn.close()


def test_md_with_frontmatter(tmp_path):
    vault, db = _make_vault(tmp_path)
    rel = "docs/guia.md"
    md = vault / rel
    md.parent.mkdir(parents=True, exist_ok=True)
    md.write_text(
        "---\ntitle: Mi Guía\nauthor: Lucas\n---\n\n# Mi Guía\n\nContenido del documento.\n",
        encoding="utf-8",
    )
    _insert_file_entry(db, rel)

    result = vault_knowledge_parse(str(vault), rel, db_path=str(db))

    assert result["title"] == "Mi Guía"
    assert result["frontmatter"]["author"] == "Lucas"
    assert "Contenido del documento" in result["content_text"]
    assert result["persisted"] is True


def test_md_no_frontmatter(tmp_path):
    vault, db = _make_vault(tmp_path)
    rel = "docs/sin_fm.md"
    md = vault / rel
    md.parent.mkdir(parents=True, exist_ok=True)
    md.write_text("# Título\n\nCuerpo sin frontmatter.\n", encoding="utf-8")
    _insert_file_entry(db, rel)

    result = vault_knowledge_parse(str(vault), rel, db_path=str(db))

    assert result["frontmatter"] == {}
    assert result["title"] == "Título"
    assert "Cuerpo sin frontmatter" in result["content_text"]


def test_md_title_from_h1(tmp_path):
    vault, db = _make_vault(tmp_path)
    rel = "docs/title_h1.md"
    md = vault / rel
    md.parent.mkdir(parents=True, exist_ok=True)
    md.write_text("# Primer H1\n\nAlgún texto.\n", encoding="utf-8")
    _insert_file_entry(db, rel)

    result = vault_knowledge_parse(str(vault), rel, db_path=str(db))

    assert result["title"] == "Primer H1"


def test_md_title_from_filename(tmp_path):
    vault, db = _make_vault(tmp_path)
    rel = "docs/nombre_archivo.md"
    md = vault / rel
    md.parent.mkdir(parents=True, exist_ok=True)
    md.write_text("Solo texto sin headings ni frontmatter.\n", encoding="utf-8")
    _insert_file_entry(db, rel)

    result = vault_knowledge_parse(str(vault), rel, db_path=str(db))

    assert result["title"] == "nombre_archivo"


def test_md_headings_levels(tmp_path):
    vault, db = _make_vault(tmp_path)
    rel = "docs/headings.md"
    md = vault / rel
    md.parent.mkdir(parents=True, exist_ok=True)
    md.write_text(
        "# H1 Título\n\nTexto.\n\n## H2 Sección\n\n### H3 Subsección\n\n## H2 Otra\n",
        encoding="utf-8",
    )
    _insert_file_entry(db, rel)

    result = vault_knowledge_parse(str(vault), rel, db_path=str(db))

    headings = result["headings"]
    assert len(headings) == 4
    levels = [h["level"] for h in headings]
    assert levels == [1, 2, 3, 2]
    texts = [h["text"] for h in headings]
    assert "H1 Título" in texts
    assert "H2 Sección" in texts
    assert "H3 Subsección" in texts


def test_md_persists_to_fts(tmp_path):
    vault, db = _make_vault(tmp_path)
    rel = "docs/fts_md.md"
    md = vault / rel
    md.parent.mkdir(parents=True, exist_ok=True)
    md.write_text("# Documento FTS\n\nPalabra clave: xenolito.\n", encoding="utf-8")
    _insert_file_entry(db, rel)

    vault_knowledge_parse(str(vault), rel, db_path=str(db))

    conn = sqlite3.connect(str(db))
    # FTS5 contentless: no permite SELECT directo, usar MATCH
    row = conn.execute(
        "SELECT rowid FROM files_fts WHERE files_fts MATCH 'xenolito'",
    ).fetchone()
    conn.close()
    assert row is not None, "FTS no encontró 'xenolito'"
