from __future__ import annotations

from dataclasses import dataclass

_SEPARATOR = "|"
_NAMESPACE = "tracecov"
_SEGMENT_COUNT = 7


@dataclass(slots=True, frozen=True)
class CoverageEvent:
    """A parsed coverage event label returned by record_schemathesis_interactions()."""

    namespace: str
    """Always "tracecov"."""
    domain: str
    """Coverage domain. Currently only "schema"; future domains may be added."""
    method: str
    """HTTP method, e.g. "GET"."""
    path: str
    """OpenAPI path template, e.g. "/users/{id}"."""
    location: str
    """Parameter location: "path", "query", "header", "cookie", "body", "form_data"."""
    parameter: str
    """Parameter name."""
    schema_path: str
    """JSON pointer to the keyword, e.g. "/minLength". Empty string for the root schema entry."""


def parse_event_label(label: str) -> CoverageEvent:
    """Parse a coverage event label into a CoverageEvent."""
    parts = label.split(_SEPARATOR)
    if len(parts) != _SEGMENT_COUNT:
        raise ValueError(
            f"Invalid coverage event label: expected {_SEGMENT_COUNT} segments separated by "
            f"'{_SEPARATOR}', got {len(parts)}. Label: {label!r}"
        )
    namespace = parts[0]
    if namespace != _NAMESPACE:
        raise ValueError(
            f"Invalid coverage event label: expected namespace {_NAMESPACE!r}, got {namespace!r}. Label: {label!r}"
        )
    return CoverageEvent(
        namespace=namespace,
        domain=parts[1],
        method=parts[2],
        path=parts[3],
        location=parts[4],
        parameter=parts[5],
        schema_path=parts[6],
    )
