"""Shared fixtures for EPO Unitary Patent Guidelines tests.

Builds a tiny on-disk corpus from hand-authored rows so the read path
is exercised end-to-end without a full EPO website scrape.

The ``up_corpus_path`` session fixture provides the on-disk path; the
``up_corpus_env`` fixture additionally monkeypatches
``UP_GUIDELINES_CORPUS_PATH`` so a single fixture covers both setup
steps for the row-18 envelope/corpus_status tests.
"""

from __future__ import annotations

import sqlite3
from datetime import UTC, datetime
from pathlib import Path

import pytest

from patent_client_agents.epo_up_guidelines.corpus.schema import DDL, SCHEMA_VERSION


@pytest.fixture(scope="session")
def up_corpus_path(tmp_path_factory: pytest.TempPathFactory) -> Path:
    out = tmp_path_factory.mktemp("up-corpus") / "up.db"
    conn = sqlite3.connect(out)
    try:
        conn.executescript(DDL)
        for key, val in (
            ("schema_version", str(SCHEMA_VERSION)),
            ("source", "fixture"),
            ("snapshot_date", datetime.now(UTC).strftime("%Y-%m-%d")),
            ("up_guidelines_year", "2026"),
        ):
            conn.execute("INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)", (key, val))
        conn.executemany(
            "INSERT INTO sections (href, section_number, title, breadcrumb, chapter, html, text) "
            "VALUES (?, ?, ?, ?, ?, ?, ?)",
            [
                (
                    "section_2_1",
                    "2.1",
                    "Eligibility (requirements under Rule 5(2) UPR)",
                    "Section 2 > 2.1",
                    "2",
                    "<div><h1>Eligibility</h1><p>For unitary effect.</p></div>",
                    "2.1 Eligibility requirements under Rule 5(2) UPR for unitary effect.",
                ),
                (
                    "section_3_2",
                    "3.2",
                    "Renewal fees for unitary patents",
                    "Section 3 > 3.2",
                    "3",
                    "<div><h1>Renewals</h1><p>Annual renewal fees.</p></div>",
                    "3.2 Renewal fees for unitary patents and annual cycle.",
                ),
                (
                    "section_4_1",
                    "4.1",
                    "Opt-out from UPC jurisdiction",
                    "Section 4 > 4.1",
                    "4",
                    "<div><h1>Opt-out</h1><p>Procedures for opt-out.</p></div>",
                    "4.1 Opt-out from UPC jurisdiction procedures.",
                ),
            ],
        )
        conn.commit()
    finally:
        conn.close()
    return out


@pytest.fixture
def up_corpus_env(monkeypatch: pytest.MonkeyPatch, up_corpus_path: Path) -> Path:
    """Point ``UP_GUIDELINES_CORPUS_PATH`` at the fixture corpus for one test."""
    monkeypatch.setenv("UP_GUIDELINES_CORPUS_PATH", str(up_corpus_path))
    return up_corpus_path
