import uuid
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any


@dataclass
class Artifact:
    """Base class for artifacts created during workflow execution."""

    id: str
    name: str
    path: Path
    artifact_type: str

    def read(self) -> str:
        """Read the artifact content."""
        return self.path.read_text()

    @classmethod
    def create(
        cls, name: str, content: str, output_dir: Path, step_name: str, step_id: str
    ) -> "Artifact":
        """Create artifact file and return instance. Override in subclasses."""
        raise NotImplementedError


class MarkdownArtifact(Artifact):
    """Markdown file artifact."""

    @classmethod
    def create(
        cls, name: str, content: str, output_dir: Path, step_name: str, step_id: str
    ) -> "MarkdownArtifact":
        artifact_id = str(uuid.uuid4())
        timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")

        # Ensure name ends with .md
        if not name.endswith(".md"):
            name = f"{name}.md"

        # Prepend step info to filename
        filename = f"step-{step_name}-{timestamp}-{step_id}-{name}"
        path = output_dir / filename
        path.write_text(content)
        return cls(id=artifact_id, name=name, path=path, artifact_type="MARKDOWN")


# Registry of artifact types
ARTIFACT_TYPES: dict[str, type[Artifact]] = {
    "MARKDOWN": MarkdownArtifact,
}


def create_artifact(
    artifact_data: dict[str, Any], output_dir: Path, step_name: str, step_id: str
) -> Artifact:
    """Create an artifact from step output data."""
    artifact_type = artifact_data.get("type")
    if artifact_type not in ARTIFACT_TYPES:
        raise ValueError(f"Unknown artifact type: {artifact_type}")

    artifact_cls = ARTIFACT_TYPES[artifact_type]
    return artifact_cls.create(
        name=artifact_data.get("name", "artifact"),
        content=artifact_data.get("content", ""),
        output_dir=output_dir,
        step_name=step_name,
        step_id=step_id,
    )
