from __future__ import annotations

from dataclasses import dataclass, asdict
from datetime import datetime, timezone
from typing import Any


SPEC_VERSION = "1.0"


@dataclass
class ActionEvent:
    id: str
    ts: str
    user_id: str
    action_type: str
    tool: str | None
    target: str | None
    decision: str | None
    status: str | None
    reason: str | None
    tags: list[str]
    metadata: dict[str, Any]
    spec_version: str = SPEC_VERSION


def now_iso() -> str:
    return datetime.now(timezone.utc).isoformat()


def to_json(event: ActionEvent) -> dict[str, Any]:
    return asdict(event)


def normalize_tags(tags: list[str] | None) -> list[str]:
    if not tags:
        return []
    return [t.strip() for t in tags if t and t.strip()]


def validate_event(obj: dict[str, Any]) -> tuple[bool, str | None]:
    required = ["id", "ts", "user_id", "action_type", "spec_version"]
    for key in required:
        if key not in obj:
            return False, f"missing: {key}"
    if obj.get("spec_version") != SPEC_VERSION:
        return False, "unsupported spec_version"
    return True, None
