"""App-owned test wiring (never touched by the scaffolder's pack refresh).

The stock pack's `_fresh_store` wipes the kit's stdlib SQLite file — but this
app runs the kit through bw_store_sqlalchemy in MANAGED mode, so the real store
IS the app's SQLAlchemy database. Without this, caddie's own tests leave
members, levels and instances behind and the conformance pack fails in ways
that have nothing to do with the code under test.

Dispose the pooled engine BEFORE unlinking the file: a pooled connection would
otherwise keep writing into the unlinked inode.
"""

from pathlib import Path

import pytest

# The pack pulls this module in with `from tests.app_conftest import *`, and
# star-import SKIPS underscore-prefixed names — which would silently drop the
# autouse fixture and leave the wipe never running. __all__ makes it explicit.
__all__ = ["_fresh_domain_db", "session", "agency"]

from app import accounts
from app.config import get_settings
from app.db import get_engine
from app.models import Base


@pytest.fixture(autouse=True)
def _fresh_domain_db(_fresh_store):
    """Runs AFTER the stock `_fresh_store` (declared dependency): wipe the
    SQLAlchemy database, then re-init the kit (bw_* tables + seed levels) and
    create the domain tables."""
    engine = get_engine()
    engine.dispose()
    url = get_settings().database_url
    if url.startswith("sqlite:///"):
        dbfile = Path(url.removeprefix("sqlite:///"))
        if dbfile.exists():
            dbfile.unlink()
    accounts.init_accounts_kit()          # bw_* tables + seed levels
    Base.metadata.create_all(engine)      # domain tables (checkfirst)
    from app.seeds.templates import load_templates
    load_templates()                      # roadmap templates the spine tests use
    yield


@pytest.fixture
def session():
    from app.db import get_session_factory
    with get_session_factory()() as s:
        yield s
        s.commit()


@pytest.fixture
def agency(kit):
    """The agency persona: composes projects and curates the dictionary.
    Clients get the plain seeded `member` level."""
    kit.bwa.create_level(kit.owner, "agency", permissions=[
        accounts.PERM_COMPOSE, accounts.PERM_CURATE,
        "instances.create", "instances.grant"])
    kit.member("pm", "agency", all_instances=True)
    return "pm"
