"""Session state management for regimen runs."""

from __future__ import annotations

import dataclasses
import hashlib
import json
import time
from dataclasses import dataclass, field
from pathlib import Path


SESSION_DIR = Path(".regimen")


@dataclass
class StepResult:
    """Result of running a single step."""

    outputs: list[dict]  # [{"command": str, "stdout": str, "stderr": str, "exit_code": int}]
    run_count: int = 1


@dataclass
class Session:
    """Persistent session state."""

    slug: str
    file_path: str
    regimen_title: str
    total_steps: int
    current_step: int = 0
    results: list[StepResult] = field(default_factory=list)
    created_at: float = 0.0
    status: str = "active"  # active, completed, aborted

    def save(self) -> None:
        """Write session state to disk."""
        SESSION_DIR.mkdir(exist_ok=True)
        path = SESSION_DIR / f"{self.slug}.json"
        path.write_text(json.dumps(dataclasses.asdict(self), indent=2))

    @staticmethod
    def load(slug: str) -> Session:
        """Load session from disk."""
        path = SESSION_DIR / f"{slug}.json"
        if not path.exists():
            raise FileNotFoundError(f"No session found: {slug}")
        data = json.loads(path.read_text())
        data["results"] = [StepResult(**r) for r in data["results"]]
        return Session(**data)


def make_slug(file_path: str) -> str:
    """Generate a short slug from file path and timestamp."""
    h = hashlib.sha1(f"{file_path}{time.time()}".encode()).hexdigest()[:8]
    name = Path(file_path).stem
    clean = name[:20].replace(" ", "-").lower()
    return f"{clean}-{h}"
