"""Run context: creates run directories, manages run state."""

from __future__ import annotations

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


def _make_run_id() -> str:
    return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")


@dataclass
class RunContext:
    repo_root: pathlib.Path
    run_id: str = field(default_factory=_make_run_id)
    apply_mode: bool = False
    contract_path: str | None = None
    task_type: str | None = None
    llm: Any | None = None

    @property
    def run_dir(self) -> pathlib.Path:
        return self.repo_root / "runs" / self.run_id

    def ensure_run_dir(self) -> pathlib.Path:
        self.run_dir.mkdir(parents=True, exist_ok=True)
        return self.run_dir

    def artifact_path(self, name: str) -> pathlib.Path:
        return self.run_dir / name

    def has_confirm_apply(self) -> bool:
        """Check if CONFIRM APPLY keyword is in the contract file."""
        if not self.contract_path:
            return False
        cp = pathlib.Path(self.contract_path)
        if not cp.is_absolute():
            cp = self.repo_root / cp
        if not cp.exists():
            return False
        text = cp.read_text(encoding="utf-8")
        return "CONFIRM APPLY" in text

    def can_apply(self) -> bool:
        """Apply requires --apply flag AND CONFIRM APPLY in contract."""
        return self.apply_mode and self.has_confirm_apply()
