"""Evidence bundle schema for Avatar plan execution (Production Evolution §8.2)."""

from __future__ import annotations

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


@dataclass
class EvidenceArtifact:
    kind: str
    path: str = ""
    sha256: str = ""
    size_bytes: int = 0
    mime: str = ""
    redacted: bool = False
    display_server: str = ""
    capture_backend: str = ""

    def to_dict(self) -> dict[str, Any]:
        payload: dict[str, Any] = {
            "kind": self.kind,
            "redacted": self.redacted,
        }
        if self.path:
            payload["path"] = self.path
        if self.sha256:
            payload["sha256"] = self.sha256
        if self.size_bytes:
            payload["size_bytes"] = self.size_bytes
        if self.mime:
            payload["mime"] = self.mime
        if self.display_server:
            payload["display_server"] = self.display_server
        if self.capture_backend:
            payload["capture_backend"] = self.capture_backend
        return payload


@dataclass
class StepEvidence:
    step_id: str
    command_type: str
    capability_id: str = ""
    status: str = "success"
    artifacts: list[EvidenceArtifact] = field(default_factory=list)
    exit_code: int | None = None
    duration_ms: int = 0

    def to_dict(self) -> dict[str, Any]:
        return {
            "step_id": self.step_id,
            "command_type": self.command_type,
            "capability_id": self.capability_id,
            "status": self.status,
            "artifacts": [artifact.to_dict() for artifact in self.artifacts],
            "exit_code": self.exit_code,
            "duration_ms": self.duration_ms,
        }


@dataclass
class EvidenceBundle:
    plan_id: str
    goal_summary: str
    collected_at: str = ""
    steps: list[StepEvidence] = field(default_factory=list)

    def __post_init__(self) -> None:
        if not self.collected_at:
            self.collected_at = datetime.now(timezone.utc).isoformat()

    def aggregate(self) -> dict[str, Any]:
        screenshot_count = 0
        files_written: list[str] = []
        urls_opened: list[str] = []
        for step in self.steps:
            for artifact in step.artifacts:
                if artifact.kind == "screenshot":
                    screenshot_count += 1
                if artifact.kind == "file_path" and artifact.path:
                    files_written.append(artifact.path)
            if step.command_type in {"browser_open_url", "open_url"}:
                for artifact in step.artifacts:
                    if artifact.path:
                        urls_opened.append(artifact.path)
        return {
            "screenshot_count": screenshot_count,
            "files_written": files_written,
            "urls_opened": urls_opened,
        }

    def to_dict(self) -> dict[str, Any]:
        return {
            "evidence_bundle": {
                "plan_id": self.plan_id,
                "goal_summary": self.goal_summary,
                "collected_at": self.collected_at,
                "steps": [step.to_dict() for step in self.steps],
                "aggregate": self.aggregate(),
            }
        }
