"""发布遥测输入的纯值校验。"""

from __future__ import annotations

import re
from typing import Any

_SAFE_CODE = re.compile(r"^[A-Za-z0-9_.:-]+$")
_STAGES = {"shadow", "canary", "active"}


def required_value(value: Any, field: str, maximum: int) -> str:
    normalized = str(value or "").strip()
    if not normalized or len(normalized) > maximum:
        raise ValueError(f"{field} is required and must be at most {maximum} characters.")
    return normalized


def safe_code(value: Any, field: str, maximum: int) -> str:
    normalized = required_value(value, field, maximum)
    if not _SAFE_CODE.fullmatch(normalized):
        raise ValueError(f"{field} contains unsupported characters.")
    return normalized


def release_stage(value: Any) -> str:
    normalized = str(value or "").strip().lower()
    if normalized not in _STAGES:
        raise ValueError("stage must be shadow, canary or active.")
    return normalized


def strict_bool(value: Any, field: str) -> bool:
    if not isinstance(value, bool):
        raise ValueError(f"{field} must be a boolean.")
    return value


def precision(confirmed: int, false_positive: int) -> float | None:
    denominator = confirmed + false_positive
    if denominator <= 0:
        return None
    return round(confirmed / denominator, 6)
