"""Shared fixtures. DB-backed tests need a throwaway Postgres database:

    TEST_DATABASE_URL=postgresql+asyncpg://user:pass@localhost:5432/neuro_test pytest

The `db` fixture wipes that database's public schema, migrates and seeds it once per run.
Tests that need it request `db`/`fresh`/`client`; without TEST_DATABASE_URL they are skipped.
"""
import os
import subprocess
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path

import pytest
import pytest_asyncio
from httpx import ASGITransport, AsyncClient
from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine

# Must be set before the app is imported: settings read DATABASE_URL at import time.
TEST_DB_URL = os.environ.get("TEST_DATABASE_URL")
if TEST_DB_URL:
    os.environ["DATABASE_URL"] = TEST_DB_URL
os.environ.setdefault("PASSWORD_HASH_ITERATIONS", "1000")  # real cost is 600k; tests log in a lot

BACKEND = Path(__file__).resolve().parent
FIXED_NOW = datetime(2026, 9, 19, 8, 0, tzinfo=timezone(timedelta(hours=6)))

# Operational tables emptied before each DB test; master data (sites, products...) is kept.
OPERATIONAL = [
    "receipt", "receipt_line", "date_sample", "delivery_discrepancy", "inspection", "batch",
    "crate", "inventory_balance", "transfer", "stock_move", "stock_move_line", "expiry_history",
    "exposure_segment", "expected_delivery", "expected_delivery_line", "audit_log",
    "idempotency_key", "sale", "sale_attribution", "risk_assessment", "recommendation",
    "action_outcome", "integration_event", "ingest_job", "engine_run", "calculation_trace",
    "stock_reconciliation", "csv_mapping", "weather_hourly", "forecast", "sim_metric", "sim_run", "job_run",
]


@pytest_asyncio.fixture(scope="session", loop_scope="session")
async def db():
    if not TEST_DB_URL:
        pytest.skip("TEST_DATABASE_URL not set")
    engine = create_async_engine(TEST_DB_URL)
    async with engine.begin() as conn:
        await conn.execute(text("DROP SCHEMA public CASCADE"))
        await conn.execute(text("CREATE SCHEMA public"))
    subprocess.run([sys.executable, "-m", "alembic", "upgrade", "head"], cwd=BACKEND, check=True,
                   env={**os.environ, "DATABASE_URL": TEST_DB_URL})
    from app.core.database import SessionLocal
    from app.modules.demo import seed

    async with SessionLocal() as s:
        await seed.seed(s)
        await s.commit()
    yield engine
    await engine.dispose()


SEED_USERS = [  # id, name, role, site id (Dhaka DC is site 1, the first outlet site 2)
    (1, "dc_staff", "DC_STAFF", 1), (2, "dc_manager", "DC_MANAGER", 1),
    (3, "outlet_staff", "OUTLET_STAFF", 2), (4, "outlet_manager", "OUTLET_MANAGER", 2),
    (5, "head_office", "HEAD_OFFICE", None),
]


async def _restore_seed_users(conn) -> None:
    """Passwords, lockouts, sessions and any extra users are part of test state too."""
    from app.core.passwords import hash_password

    await conn.execute(text("DELETE FROM app_user WHERE id > 5"))
    for uid, name, role, site in SEED_USERS:
        await conn.execute(text(
            "UPDATE app_user SET name = :n, email = :e, role = :r, site_id = :s, "
            "password_hash = :h, must_change_password = true, is_active = true, "
            "failed_attempts = 0, locked_until = NULL, token_version = 1, "
            "password_changed_at = NULL WHERE id = :i"),
            {"n": name, "e": f"{name}@neuro.local", "r": role, "s": site,
             "h": hash_password("123456"), "i": uid})


@pytest_asyncio.fixture(loop_scope="session")
async def fresh(db):
    """Empty operational tables and pin the SIM clock to FIXED_NOW (2026-09-19 08:00 Dhaka)."""
    async with db.begin() as conn:
        await conn.execute(text(
            "TRUNCATE " + ", ".join(OPERATIONAL) + " RESTART IDENTITY CASCADE"))
        await conn.execute(text("UPDATE app_clock SET mode = 'SIM', sim_now = :t"),
                           {"t": FIXED_NOW})
        await _restore_seed_users(conn)
        # drop external-id mappings a test added; keep the seeded ones (site code, SKU, SUP<id>)
        await conn.execute(text(
            "DELETE FROM ext_mapping WHERE NOT ("
            "(entity = 'site' AND external_id IN (SELECT code FROM site)) OR "
            "(entity = 'product' AND external_id IN (SELECT sku FROM product) "
            " AND external_id IN (SELECT p.sku FROM product p WHERE p.id = internal_id)) OR "
            "(entity = 'supplier' AND external_id LIKE 'SUP%' AND external_id <> 'SUP99'))"))
    yield db


@pytest_asyncio.fixture(loop_scope="session")
async def client(fresh):
    from app.main import app

    async with AsyncClient(transport=ASGITransport(app=app), base_url="http://t") as c:
        yield c


async def login_as(client: AsyncClient, email: str, password: str = "123456") -> dict:
    r = await client.post("/api/v1/auth/login", json={"email": email, "password": password})
    assert r.status_code == 200, r.text
    return {"Authorization": f"Bearer {r.json()['access_token']}"}


async def login(client: AsyncClient, username: str) -> dict:
    """Headers for a seeded actor by short name (dc_staff, head_office, ...): their makeshift
    email is <name>@neuro.local and the starting password is 123456."""
    return await login_as(client, f"{username}@neuro.local")


@pytest_asyncio.fixture(loop_scope="session")
async def dc(client, db):
    """DC staff session with receiving helpers."""
    from testkit import Dc

    return Dc(client, db, await login(client, "dc_staff"))


@pytest_asyncio.fixture(loop_scope="session")
async def outlet(client):
    """Headers for the seeded outlet staff and manager (both at the first outlet)."""
    return {"staff": await login(client, "outlet_staff"),
            "manager": await login(client, "outlet_manager")}
