"""Shared fixtures for the site-ng test suite.

Two layers of tests live here:

  unit/         pure-logic tests (slugs, labels, compatibility heuristics,
                bot detection). No app, no DB — just import and assert.

  integration/  drive the real Flask app via test_client against the local
                DEV MIRROR database (arpartsfinder_dev). These exercise the
                actual user workflows: add parts to a build, save it, view
                the chip / the /build page / the public /b/<code> page, and
                the owner-only controls. They are marked `integration` +
                `db` and SKIP cleanly when the dev DB isn't reachable, so
                `pytest` never hard-fails on a machine without the mirror.

DB safety: the dev mirror is throwaway (re-snapshotted from prod). Even so,
integration tests are self-cleaning — every build/user a test creates is
torn down in fixture teardown (by owner_user_id for owned builds, by
tracked share-code for anonymous ones). Tests only ever WRITE rows they
own; they never touch prod and never mutate the shared `parts` data.
"""
import sys
import uuid
from pathlib import Path

import pytest

# Make `import ngsite` work no matter where pytest is invoked from (repo
# root via the aggregate pytest.ini, or `cd site-ng && pytest`). The
# site-ng package root is this file's grandparent: tests/ -> site-ng/.
SITE_NG_ROOT = Path(__file__).resolve().parents[1]
if str(SITE_NG_ROOT) not in sys.path:
    sys.path.insert(0, str(SITE_NG_ROOT))


# --------------------------------------------------------------------------- #
# App / client
# --------------------------------------------------------------------------- #
@pytest.fixture(scope="session")
def app():
    """A dev-mode app instance. NGSITE_ENV=dev keeps the debugger off the
    prod path while skipping the prod-only PUBLIC_URL_ROOT boot assertion,
    and points config at the local mirror DB via config.ini."""
    from ngsite import create_app
    application = create_app({"NGSITE_ENV": "dev", "TESTING": True})
    return application


@pytest.fixture()
def client(app):
    """A fresh test client (empty session) per test."""
    return app.test_client()


# --------------------------------------------------------------------------- #
# Database (integration only) — a raw connection independent of Flask's
# request-scoped `g`, so setup/teardown work outside the request cycle.
# --------------------------------------------------------------------------- #
@pytest.fixture(scope="session")
def db_conn(app):
    import pymysql
    cfg = app.config
    try:
        conn = pymysql.connect(
            host=cfg["DB_HOST"], port=cfg["DB_PORT"],
            user=cfg["DB_USER"], password=cfg["DB_PASSWORD"],
            database=cfg["DB_NAME"], charset="utf8mb4",
            cursorclass=pymysql.cursors.DictCursor,
            autocommit=True, connect_timeout=5, read_timeout=15)
    except Exception as e:                       # pragma: no cover - env-dependent
        pytest.skip(f"dev mirror DB unavailable ({cfg.get('DB_NAME')}): {e}")
    yield conn
    conn.close()


@pytest.fixture()
def sample_parts(db_conn):
    """A handful of real in-stock parts from the dev mirror, used as the
    items a test build is assembled from. Skips if the mirror is empty."""
    with db_conn.cursor() as cur:
        cur.execute(
            "SELECT id, type, company, price, description "
            "FROM parts "
            "WHERE instock=1 AND (hidden IS NULL OR hidden=0) "
            "  AND price > 0 AND description <> '' "
            "ORDER BY id LIMIT 5")
        rows = cur.fetchall()
    if len(rows) < 2:
        pytest.skip("need >=2 in-stock parts in the dev mirror")
    return rows


@pytest.fixture()
def make_user(db_conn):
    """Factory creating throwaway app_user rows. All users created through
    it — and every build/build_item they own — are deleted on teardown."""
    created = []

    def _make(email=None):
        email = email or f"pytest+{uuid.uuid4().hex[:12]}@example.invalid"
        with db_conn.cursor() as cur:
            cur.execute(
                "INSERT INTO app_user (email, created) VALUES (%s, NOW())",
                (email,))
            uid = cur.lastrowid
        created.append(uid)
        return {"id": uid, "email": email}

    yield _make

    for uid in created:
        with db_conn.cursor() as cur:
            cur.execute("SELECT id FROM build WHERE owner_user_id=%s", (uid,))
            bids = [r["id"] for r in cur.fetchall()]
            for bid in bids:
                cur.execute("DELETE FROM build_item WHERE build_id=%s", (bid,))
            if bids:
                cur.execute("DELETE FROM build WHERE owner_user_id=%s", (uid,))
            cur.execute("DELETE FROM app_user WHERE id=%s", (uid,))


@pytest.fixture()
def track_codes(db_conn):
    """Collects share-codes of ANONYMOUS builds a test creates (owner_user_id
    is NULL, so make_user's owner-keyed teardown won't catch them) and
    deletes them — and their items — afterwards."""
    codes = []
    yield codes
    for code in codes:
        with db_conn.cursor() as cur:
            cur.execute("SELECT id FROM build WHERE code=%s", (code,))
            for r in cur.fetchall():
                cur.execute("DELETE FROM build_item WHERE build_id=%s",
                            (r["id"],))
            cur.execute("DELETE FROM build WHERE code=%s", (code,))


# --------------------------------------------------------------------------- #
# Helpers (imported by integration tests)
# --------------------------------------------------------------------------- #
def login(client, user):
    """Put a user into the client's session without the magic-link round
    trip — mirrors exactly what auth.py writes on a real login."""
    with client.session_transaction() as sess:
        sess["user_id"] = int(user["id"])
        sess["user_email"] = user["email"]


def add_part(client, parts_id, qty=1):
    """POST a part into the active draft `qty` times (mirrors clicking
    +Add). Returns the last response."""
    resp = None
    for _ in range(qty):
        resp = client.post("/build/add", data={"id": parts_id})
    return resp
