"""Blog draft data access for the web dashboard."""

from __future__ import annotations

import json

from ietf_analyzer.db import Database


def get_all_blog_drafts(db: Database) -> list[dict]:
    """Return all blog drafts, newest first."""
    drafts = db.all_blog_drafts()
    for d in drafts:
        try:
            d["tags"] = json.loads(d.get("tags") or "[]")
        except (json.JSONDecodeError, TypeError):
            d["tags"] = []
    return drafts


def get_blog_draft_detail(db: Database, draft_id: int) -> dict | None:
    """Return a single blog draft with parsed tags."""
    d = db.get_blog_draft(draft_id)
    if not d:
        return None
    try:
        d["tags"] = json.loads(d.get("tags") or "[]")
    except (json.JSONDecodeError, TypeError):
        d["tags"] = []
    return d
