"""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` (caddie runbook §5, learned on punchlist).
# __all__ makes it explicit.
__all__ = ["_fresh_domain_db"]

from app import accounts, db
from app.config import get_settings
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 (a no-op after init's sqlite create_all, kept explicit)."""
    db.reset_for_tests()
    url = get_settings().database_url
    if url.startswith("sqlite:///"):
        dbfile = Path(url.removeprefix("sqlite:///"))
        if dbfile.exists():
            dbfile.unlink()
    accounts.init_accounts_kit()
    Base.metadata.create_all(db.get_engine())
    yield
