"""Schemathesis extensions for the v3 API contract tests (ENG-2191).

Two jobs, both generic over the contract rather than per endpoint:

1. Teach Schemathesis the ``cuid2`` string format every v3 identifier declares. Without it an
   unknown format degrades to an arbitrary string — including values like ``""`` or ``"0"`` that
   route somewhere other than the operation under test, producing failures that say nothing about
   the contract. ``web-url`` (a creative's link Destination) is registered for the same reason: a
   generated host would mostly be one the API refuses, so the write would never be exercised.

2. Point identifiers at the seeded data so authenticated endpoints answer with real payloads
   instead of a wall of 401/403s. Substitution is keyed by parameter name and operationId, from the
   map ``db:seed:contract`` writes (``fixtures.json``) — nothing here is registered per test, so a
   newly documented endpoint is exercised the moment it lands in the bundle. An id the map does not
   mention keeps its generated cuid2 and gets the documented 403, which is still a contract check.

Everything runs in ``before_call`` because that is the one place a value always wins: cases derived
from the spec's own examples never reach ``map_query`` / ``map_path_parameters`` with a populated
dict, so overriding there would silently skip exactly the operations that carry examples.
"""

from __future__ import annotations

import json
import os
from pathlib import Path
from typing import Any

import schemathesis
from hypothesis import strategies as st

FIXTURES_ENV_VAR = "V3_CONTRACT_FIXTURES"
DEFAULT_FIXTURES_PATH = Path(__file__).with_name("fixtures.json")

# cuid2 as the v3 routes validate it (`z.cuid2()` in packages/types/common.ts): lowercase
# alphanumeric. The fixed length keeps generated ids visually distinct from real ones in reports.
CUID2_STRATEGY = st.from_regex(r"\A[a-z][a-z0-9]{23}\Z")

# `web-url` as the creative routes validate it (`isWebUrl` in packages/types/web-url.ts): http(s) with a
# real host. A fixed domain keeps every generated link valid; the path varies.
WEB_URL_STRATEGY = st.from_regex(r"\Ahttps://www\.example\.com(/[a-z0-9-]{1,16})?\Z")

# Any parameter or body field with this name identifies the tenant, on every current and future v3
# operation, so it is substituted globally rather than per operation.
WORKSPACE_FIELD = "workspaceId"


def _load_fixtures() -> dict[str, Any]:
    path = Path(os.environ.get(FIXTURES_ENV_VAR) or DEFAULT_FIXTURES_PATH)
    # `ValueError` rather than `json.JSONDecodeError` alone: a truncated write, a hand-edit, and a file
    # that is not UTF-8 all reach the reader as the same problem as a missing one — "your fixtures are
    # not usable, re-seed" — and `UnicodeDecodeError` is a ValueError that JSONDecodeError misses.
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except (OSError, ValueError) as exc:
        raise RuntimeError(
            f"Contract fixtures at {path} are missing or unreadable. Run "
            "`pnpm --filter=@formbricks/database db:seed:contract` first, or point "
            f"{FIXTURES_ENV_VAR} at the file it wrote. Running without it would test an empty "
            "workspace and report a green run that proves nothing."
        ) from exc


_FIXTURES = _load_fixtures()
# Explicit rather than `_FIXTURES["workspaceId"]`: a map written by an older revision of the seed raises
# a bare KeyError out of hook import, which reaches the developer as an opaque "failed to load
# SCHEMATHESIS_HOOKS" instead of the one instruction that fixes it.
if not _FIXTURES.get(WORKSPACE_FIELD):
    raise RuntimeError(
        f"Contract fixtures at {os.environ.get(FIXTURES_ENV_VAR) or DEFAULT_FIXTURES_PATH} carry no "
        f"'{WORKSPACE_FIELD}'. Re-run `pnpm --filter=@formbricks/database db:seed:contract` to "
        "regenerate them. Running without it would test an empty workspace and report a green run "
        "that proves nothing."
    )
WORKSPACE_ID: str = _FIXTURES[WORKSPACE_FIELD]
# Defaults keyed by parameter name, used by every operation without a more specific entry.
READ_IDS: dict[str, str] = _FIXTURES.get("read", {})
# Per-operationId overrides: {"deleteSurveyV3": {"path": {...}, "body": {...}}}. Mutating operations
# get their own disposable resource here so a DELETE cannot decide what a GET elsewhere sees.
# Values are usually ids, but may be whole objects or lists — a dashboard save carries its widget list.
OPERATION_IDS: dict[str, dict[str, dict[str, Any]]] = _FIXTURES.get("operations", {})

schemathesis.openapi.format("cuid2", CUID2_STRATEGY)
schemathesis.openapi.format("web-url", WEB_URL_STRATEGY)


def _operation_id(case: Any) -> str | None:
    definition = getattr(case.operation, "definition", None)
    raw = getattr(definition, "raw", None)
    return raw.get("operationId") if isinstance(raw, dict) else None


def _substitute(container: Any, overrides: dict[str, Any], defaults: dict[str, str]) -> None:
    """Replace known identifiers in place, leaving unknown fields to the generated data.

    Recursive because identifiers are not always top level: `POST /api/v3/surveys/validate` carries
    the workspace under `data.workspaceId`, and a workflow definition references its trigger survey
    from inside `definition.trigger.config`. Every name handled here means the same thing wherever it
    appears in this API, so descending is safe.
    """
    if isinstance(container, list):
        for item in container:
            _substitute(item, overrides, defaults)
        return

    if not isinstance(container, dict):
        return

    for name, value in container.items():
        # Per-operation overrides come first, including for `workspaceId`: an operation that wants a
        # foreign workspace — to assert the documented cross-tenant 403 — has to be able to say so,
        # and `operations` is the map documented as winning over the defaults.
        if name in overrides:
            container[name] = overrides[name]
        elif name == WORKSPACE_FIELD:
            container[name] = WORKSPACE_ID
        elif name in defaults:
            container[name] = defaults[name]
        else:
            _substitute(value, overrides, defaults)


@schemathesis.hook
def before_call(ctx: Any, case: Any, transport_kwargs: dict[str, Any]) -> None:  # noqa: ARG001
    operation = OPERATION_IDS.get(_operation_id(case) or "", {})

    _substitute(case.path_parameters, operation.get("path", {}), READ_IDS)
    _substitute(case.query, operation.get("query", {}), READ_IDS)
    # Body identifiers are substituted too: `POST /api/v3/surveys` carries its workspaceId in the
    # body, and `POST /api/v3/tags/{tagId}/merge` names the surviving tag there. Read defaults apply
    # so a generated workflow definition points its trigger at a survey that exists.
    _substitute(case.body, operation.get("body", {}), READ_IDS)
