"""Isolated database fixture for the coverage expansion suite."""

import re
from collections.abc import Iterator
from datetime import date
from pathlib import Path

import pytest
from sqlalchemy import MetaData, Table, text

from . import helpers
from .helpers import Store, find_ddl_file


@pytest.fixture
def store(tmp_path: Path) -> Iterator[Store]:
    """Provide a fresh local database, never the configured FINOPS database."""
    value = Store(tmp_path / "coverage.db")
    yield value
    value.close()


@pytest.fixture(autouse=True)
def no_external_connections(monkeypatch: pytest.MonkeyPatch) -> None:
    """Fail any real HTTP request or Google default-credential discovery."""

    def forbidden(*args: object, **kwargs: object) -> None:
        del args, kwargs
        raise AssertionError(
            "External I/O is forbidden in the coverage expansion tests"
        )

    monkeypatch.setattr("requests.sessions.Session.request", forbidden)
    monkeypatch.setattr("google.auth.default", forbidden)


@pytest.fixture
def governance(
    store: Store, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> dict[str, Table]:
    """Use real migration columns/keys with the existing SQLite DDL adapter.

    MariaDB ENUM, FK, collation and FOR UPDATE semantics are NOT emulated.
    """
    ddl = find_ddl_file("040_create_tag_governance.sql").read_text()
    storage = (
        find_ddl_file("044_create_tag_coverage.sql").read_text().split("DELIMITER")[0]
    )
    statements = re.sub(r"--[^\n]*", "", ddl + "\n" + storage).split(";")
    tables: dict[str, Table] = {}
    for index, statement in enumerate(statements):
        if not statement.strip().startswith("CREATE TABLE"):
            continue
        filename = tmp_path / f"table_{index}.sql"
        filename.write_text(statement)
        with monkeypatch.context() as scoped:
            scoped.setattr(
                helpers, "find_ddl_file", lambda *a, target=filename, **kw: target
            )
            table = store.ddl(filename.name)
            tables[table.name] = table
    quality = re.sub(
        r"--[^\n]*", "", find_ddl_file("046_tag_coverage_quality.sql").read_text()
    )
    with store.engine.begin() as conn:
        for statement in quality.split(";"):
            match = re.match(r"\s*ALTER TABLE (\w+)\s+(.*)", statement, re.DOTALL)
            if match:
                for column in match[2].split(","):
                    conn.execute(
                        text(
                            f"ALTER TABLE {match[1]} "
                            + column.strip()
                            .replace("IF NOT EXISTS ", "")
                            .replace("TINYINT(1)", "INTEGER")
                        )
                    )
    metadata = MetaData()
    tables = {
        name: Table(name, metadata, autoload_with=store.engine) for name in tables
    }
    with store.engine.begin() as conn:
        conn.execute(
            tables["finops_tag_provider"]
            .insert()
            .values(provider="GCP", historical_through=date(2026, 11, 11))
        )
        views = find_ddl_file("041_create_tag_governance_views.sql").read_text()
        views = re.sub(r"--[^\n]*", "", views).replace(
            "CREATE OR REPLACE VIEW", "CREATE VIEW"
        )
        raw_connection = conn.connection.driver_connection
        assert raw_connection is not None
        raw_connection.create_function("CHAR_LENGTH", 1, len)
        for statement in views.split(";"):
            if statement.strip():
                conn.execute(text(statement))
    return tables
