"""Context dataclass and JSON serialization."""

from __future__ import annotations

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


@dataclass
class Context:
    message: str = ""
    task: str = ""
    approaches_tried: list[str] = field(default_factory=list)
    current_approach: str = ""
    decisions: list[str] = field(default_factory=list)
    next_steps: list[str] = field(default_factory=list)
    files_changed: list[str] = field(default_factory=list)
    git_diff_summary: str = ""
    handoff_to: str | None = None
    handoff_note: str | None = None
    tags: list[str] = field(default_factory=list)
    branch: str = ""
    id: str = field(default_factory=lambda: str(uuid.uuid4()))
    timestamp: str = field(
        default_factory=lambda: datetime.now(timezone.utc).isoformat()
    )

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> Context:
        known_fields = {f.name for f in cls.__dataclass_fields__.values()}
        filtered = {k: v for k, v in data.items() if k in known_fields}
        return cls(**filtered)

    def filename(self) -> str:
        """Generate a cross-platform safe filename from the timestamp."""
        ts = self.timestamp.replace(":", "-").replace("+", "_")
        return f"{ts}.json"
