"""Session state: save and load the weekly editorial workflow state."""
import json
from datetime import datetime
from pathlib import Path

SESSIONS_DIR = Path(__file__).parent.parent / "sessions"

STEPS = ["research", "sources", "storyline", "draft", "quality", "publication", "done"]


def new_session() -> dict:
    return {
        "date": datetime.today().strftime("%Y-%m-%d"),
        "step": "research",
        "research": None,
        "sources": None,
        "storyline": None,
        "draft": None,
        "quality": None,
        "publication": None,
    }


def save(session: dict) -> None:
    SESSIONS_DIR.mkdir(exist_ok=True)
    path = SESSIONS_DIR / f"{session['date']}.json"
    with open(path, "w") as f:
        json.dump(session, f, ensure_ascii=False, indent=2)


def load_latest() -> dict | None:
    if not SESSIONS_DIR.exists():
        return None
    files = sorted(SESSIONS_DIR.glob("*.json"), reverse=True)
    if not files:
        return None
    with open(files[0]) as f:
        return json.load(f)
