import json
from pathlib import Path
from dataclasses import dataclass, asdict
from typing import Any, Dict, Optional

STORAGE_DIR = Path("storage")
STORAGE_DIR.mkdir(exist_ok=True)

@dataclass
class JobDoc:
    id: str
    scenario: Dict[str, Any]

    def save(self):
        path = STORAGE_DIR / self.id / "job.json"
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(json.dumps(asdict(self), ensure_ascii=False, indent=2), encoding="utf-8")

    @staticmethod
    def load(job_id: str) -> Optional["JobDoc"]:
        path = STORAGE_DIR / job_id / "job.json"
        if not path.exists():
            return None
        data = json.loads(path.read_text(encoding="utf-8"))
        return JobDoc(**data)
