"""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 (a SQLite file under the test data dir; prod
is the Postgres sidecar). This fixture wipes THAT database around each test:
dispose the pooled engine first (a pooled connection would otherwise keep
writing into the unlinked inode), then rebuild schema + seeds.
"""

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 silently drops an autouse
# fixture named `_something` (learned the hard way: the wipe never ran and the
# view-as tests leaked members into each other). __all__ makes it explicit.
__all__ = ["_fresh_domain_db"]

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): full clean of the
    SQLAlchemy database, then kit re-init (registers bw_* tables + seeds levels)
    and domain create_all."""
    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)
    yield
