# retoor <retoor@molodetz.nl>
from __future__ import annotations

import json
import logging
from dataclasses import dataclass, field
from typing import Any, Optional

logger = logging.getLogger(__name__)

KIND_STAGE: str = "stage"
KIND_LOG: str = "log"
KIND_FILE: str = "file"
KIND_SIGNAL: str = "signal"
KIND_AI: str = "ai"
KIND_IMAGE: str = "image"
KIND_DOM: str = "dom"
KIND_PROGRESS: str = "progress"
KIND_SCORE: str = "score"
KIND_REPORT: str = "report"
KIND_ERROR: str = "error"
KIND_DONE: str = "done"

STAGE_RESOLVE: str = "resolve"
STAGE_ACQUIRE: str = "acquire"
STAGE_INVENTORY: str = "inventory"
STAGE_STATIC: str = "static-analysis"
STAGE_AI: str = "ai-review"
STAGE_IMAGES: str = "image-review"
STAGE_DOM: str = "dom-analysis"
STAGE_SCORE: str = "scoring"
STAGE_REPORT: str = "report"


@dataclass(frozen=True)
class WorkerEvent:
    kind: str
    message: str
    data: dict[str, Any] = field(default_factory=dict)

    def to_json(self) -> str:
        return json.dumps({"kind": self.kind, "message": self.message, "data": self.data}, ensure_ascii=False)

    @staticmethod
    def parse(line: str) -> Optional["WorkerEvent"]:
        line = line.strip()
        if not line or not line.startswith("{"):
            return None
        try:
            body = json.loads(line)
        except json.JSONDecodeError as error:
            logger.debug("Unparseable worker line: %s (%s)", line[:120], error)
            return None
        kind = body.get("kind")
        message = body.get("message")
        data = body.get("data")
        if not isinstance(kind, str) or not isinstance(message, str):
            return None
        return WorkerEvent(kind=kind, message=message, data=data if isinstance(data, dict) else {})
