import json
import re

import pytest
from httpx import ASGITransport, AsyncClient

from app.core import error_codes as errors
from app.core.auth import create_token
from app.core.config import settings
from app.core.models import AppUser
from app.main import app

OPEN_PATHS = {"/api/v1/auth/login"}  # the only endpoint reachable without credentials

# (method, path, roles allowed). Every endpoint must enforce exactly these roles.
ROLE_MATRIX = [
    ("POST", "/api/v1/receipts", {"DC_STAFF"}),
    ("POST", "/api/v1/receipts/1/lines", {"DC_STAFF"}),
    ("POST", "/api/v1/receipt-lines/1/date-samples", {"DC_STAFF"}),
    ("POST", "/api/v1/receipts/1/confirm", {"DC_STAFF"}),
    ("GET", "/api/v1/receipts/1/labels", {"DC_STAFF"}),
    ("POST", "/api/v1/transfers/dispatch", {"DC_STAFF"}),
    ("POST", "/api/v1/transfers/1/load", {"DC_STAFF", "OUTLET_STAFF", "OUTLET_MANAGER"}),
    ("POST", "/api/v1/transfers/1/depart", {"DC_STAFF", "OUTLET_STAFF", "OUTLET_MANAGER"}),
    ("POST", "/api/v1/transfers/1/arrive", {"OUTLET_STAFF", "OUTLET_MANAGER"}),
    ("GET", "/api/v1/expected-deliveries", {"DC_STAFF", "DC_MANAGER"}),
    ("POST", "/api/v1/expected-deliveries", {"HEAD_OFFICE"}),
    ("POST", "/api/v1/delivery-discrepancies/1/acknowledge", {"DC_MANAGER"}),
    ("GET", "/api/v1/scan/C000001001",
     {"DC_STAFF", "DC_MANAGER", "OUTLET_STAFF", "OUTLET_MANAGER"}),
    ("GET", "/api/v1/today?site_id=1", {"OUTLET_MANAGER"}),
    ("POST", "/api/v1/recommendations/1/decide", {"OUTLET_MANAGER"}),
    ("GET", "/api/v1/reports/waste", {"HEAD_OFFICE"}),
    ("GET", "/api/v1/reports/impact", {"HEAD_OFFICE"}),
    ("GET", "/api/v1/reports/reconciliation", {"HEAD_OFFICE"}),
    ("GET", "/api/v1/reports/delivery-exceptions", {"DC_MANAGER", "HEAD_OFFICE"}),
    ("POST", "/api/v1/demo/clock", {"HEAD_OFFICE"}),
    ("POST", "/api/v1/demo/reset", {"HEAD_OFFICE"}),
    ("POST", "/api/v1/sim/run", {"HEAD_OFFICE"}),
    ("POST", "/api/v1/connect/csv/sale?source_system=pos", {"HEAD_OFFICE"}),
]
ALL_ROLES = {"DC_STAFF", "DC_MANAGER", "OUTLET_STAFF", "OUTLET_MANAGER", "HEAD_OFFICE"}
ROLE_MATRIX += [  # open to every logged-in role
    ("GET", "/api/v1/batches/1", ALL_ROLES),
    ("GET", "/api/v1/batches/1/history", ALL_ROLES),
    ("GET", "/api/v1/suppliers", ALL_ROLES),
    ("GET", "/api/v1/product-categories", ALL_ROLES),
    ("GET", "/api/v1/products", ALL_ROLES),
    ("GET", "/api/v1/locations", ALL_ROLES),
    ("GET", "/api/v1/transfers", ALL_ROLES),
    ("GET", "/api/v1/transfers/1", ALL_ROLES),
]
ROLE_MATRIX += [("GET", "/api/v1/connect/events", {"HEAD_OFFICE"})]
ROLE_MATRIX += [
    ("GET", "/api/v1/batches", ALL_ROLES),
    ("GET", "/api/v1/sites", ALL_ROLES),
    ("POST", "/api/v1/products", {"DC_MANAGER", "HEAD_OFFICE"}),
    ("PATCH", "/api/v1/products/1", {"DC_MANAGER", "HEAD_OFFICE"}),
    ("POST", "/api/v1/transfers/dispatch/preview", {"DC_STAFF"}),
    ("POST", "/api/v1/transfers/1/approve", {"DC_MANAGER"}),
    ("GET", "/api/v1/connect/csv-mappings/pos/sale", {"HEAD_OFFICE"}),
    ("PUT", "/api/v1/connect/csv-mappings/pos/sale", {"HEAD_OFFICE"}),
    ("DELETE", "/api/v1/connect/csv-mappings/pos/sale", {"HEAD_OFFICE"}),
    ("GET", "/api/v1/connect/id-mappings/pos/site", {"HEAD_OFFICE"}),
    ("PUT", "/api/v1/connect/id-mappings/pos/site", {"HEAD_OFFICE"}),
    ("DELETE", "/api/v1/connect/id-mappings/pos/site?external_id=x", {"HEAD_OFFICE"}),
    ("POST", "/api/v1/connect/id-mappings/pos/site/csv", {"HEAD_OFFICE"}),
    ("GET", "/api/v1/recommendations", {"OUTLET_MANAGER", "HEAD_OFFICE"}),
    ("GET", "/api/v1/recommendations/1", {"OUTLET_MANAGER", "HEAD_OFFICE"}),
    ("POST", "/api/v1/batches/1/write-off",
     {"DC_STAFF", "DC_MANAGER", "OUTLET_STAFF", "OUTLET_MANAGER"}),
    ("GET", "/api/v1/system/status", ALL_ROLES),
    ("GET", "/api/v1/auth/me", ALL_ROLES),
    ("POST", "/api/v1/auth/change-password", ALL_ROLES),
    ("GET", "/api/v1/users", {"HEAD_OFFICE"}),
    ("POST", "/api/v1/users", {"HEAD_OFFICE"}),
    ("PATCH", "/api/v1/users/1", {"HEAD_OFFICE"}),
    ("POST", "/api/v1/users/1/reset-password", {"HEAD_OFFICE"}),
]


def _routes():
    for path, item in app.openapi()["paths"].items():
        if path.startswith("/api/v1/") and path not in OPEN_PATHS:
            for method in item:
                yield method.upper(), path


def _client():
    return AsyncClient(transport=ASGITransport(app=app), base_url="http://t")


def _token(role: str, site_id: int | None) -> dict:
    user = AppUser(id=1, name="t", role=role, site_id=site_id)
    return {"Authorization": f"Bearer {create_token(user)}"}


def test_all_required_endpoints_registered():
    routes = set(_routes()) | {("POST", "/api/v1/auth/login")}
    assert len(routes) == 58, sorted(routes)  # 52 + auth me/change-password + 4 user routes


def test_no_markdown_or_sticker_endpoints():
    for _, path in _routes():
        assert "markdown" not in path and "sticker" not in path, path


@pytest.mark.parametrize("method,path", sorted(_routes()))
async def test_anonymous_gets_401(method, path):
    url = re.sub(r"\{[^}]+\}", "1", path)  # path params accept any text
    async with _client() as c:
        r = await c.request(method, url, json={})
    assert r.status_code == 401, (method, url, r.text)
    assert r.json()["error"] == errors.UNAUTHENTICATED


@pytest.mark.parametrize("method,path,allowed", ROLE_MATRIX)
async def test_disallowed_roles_get_403(method, path, allowed):
    async with _client() as c:
        for role in sorted(ALL_ROLES - allowed):
            r = await c.request(method, path, json={}, headers=_token(role, 1))
            assert r.status_code == 403, (role, method, path, r.status_code)
            assert r.json()["error"] == errors.FORBIDDEN


def test_role_matrix_covers_every_non_auth_route():
    covered = {(m, re.sub(r"\?.*", "", p)) for m, p, _ in ROLE_MATRIX}
    covered = {(m, re.sub(r"/(1|C000001001|sale)(?=/|$)", "/{x}", p)) for m, p in covered}
    covered |= {(m, re.sub(r"/pos/(\{x\}|site)(?=/|$)", "/{x}/{x}", p)) for m, p in covered}
    for method, path in _routes():
        if path.startswith("/api/v1/connect/webhook") or path.startswith("/api/v1/connect/rest"):
            continue  # SYSTEM auth, tested separately
        norm = re.sub(r"/\{[^}]+\}", "/{x}", path)
        assert (method, norm) in covered, (method, path)


async def test_wrong_site_forbidden(client):
    from conftest import login

    r = await client.get("/api/v1/today?site_id=3", headers=await login(client, "outlet_manager"))
    assert r.status_code == 403 and r.json()["error"] == errors.FORBIDDEN_SITE


async def test_dismissed_requires_reason(client):
    from conftest import login

    r = await client.post("/api/v1/recommendations/1/decide", json={"decision": "DISMISSED"},
                          headers=await login(client, "outlet_manager"))
    assert r.status_code == 422 and r.json()["error"] == errors.VALIDATION_FAILED


def test_followed_price_is_optional():
    from app.modules.risk.schemas import DecideIn

    assert DecideIn(decision="FOLLOWED").applied_price is None


SALE = {"event_id": "e1", "outlet_ext_id": "OUT-DHN", "sku_ext_id": "MLK1L", "qty": "2",
        "unit_price": "105.00", "sold_at": "2026-10-05T10:00:00+06:00"}


async def test_webhook_rejects_a_bad_signature():
    body = json.dumps(SALE).encode()
    async with _client() as c:
        for sig in (None, "nope"):
            headers = {"content-type": "application/json", **({"X-Signature": sig} if sig else {})}
            r = await c.post("/api/v1/connect/webhook/pos", content=body, headers=headers)
            assert r.status_code == 401 and r.json()["error"] == errors.UNAUTHENTICATED


async def test_rest_rejects_a_wrong_system_token_and_unknown_entity():
    async with _client() as c:
        bad = await c.post("/api/v1/connect/rest/pos/sale", json=SALE,
                           headers={"Authorization": "Bearer wrong"})
        unknown = await c.post("/api/v1/connect/rest/pos/bogus", json=SALE,
                               headers={"Authorization": f"Bearer {settings.system_token}"})
    assert bad.status_code == 401
    assert unknown.status_code == 404 and unknown.json()["error"] == errors.UNKNOWN_CODE
