from __future__ import annotations

import json
import re
import sys


def print_json(data: dict | list) -> None:
    """Print JSON to stdout."""
    json.dump(data, sys.stdout, ensure_ascii=False, default=str)
    print()


def print_error(error: str, message: str, status: int = 1) -> None:
    """Print structured error to stderr."""
    json.dump(
        {"error": error, "message": message, "status": status},
        sys.stderr,
        ensure_ascii=False,
    )
    print(file=sys.stderr)


def is_tty() -> bool:
    """Return True when stdout is an interactive terminal."""
    return sys.stdout.isatty()


_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
_CODE_RE = re.compile(r"^[a-zA-Z0-9_-]+$")


def validate_date(value: str, name: str = "date") -> str:
    """Validate a YYYY-MM-DD date string. Exits on invalid input."""
    if not _DATE_RE.match(value):
        print_error("invalid_input", f"{name} must be in YYYY-MM-DD format, got: {value}", 1)
        raise SystemExit(1)
    return value


def validate_code(value: str, name: str = "code") -> str:
    """Validate an alphanumeric code string. Exits on invalid input."""
    if not _CODE_RE.match(value):
        print_error("invalid_input", f"{name} must be alphanumeric (hyphens/underscores allowed), got: {value}", 1)
        raise SystemExit(1)
    return value
