import json, os

OUTDIR = os.path.dirname(os.path.abspath(__file__))

def split_sections(md):
    sections = []
    parts = md.strip().split("\n## ")
    for i, p in enumerate(parts):
        p = p.lstrip("# ").strip() if i == 0 and p.startswith("## ") else p
        if p.startswith("## "):
            p = p[3:]
        if not p.strip():
            continue
        title, _, body = p.partition("\n")
        sections.append({"title": title.strip(), "content": body.strip() + "\n"})
    return sections

def build_and_save(topic, slug, category_id, summary, references, short_md, long_md, clinical_md):
    data = {
        "topic": topic,
        "slug": slug,
        "category_id": category_id,
        "summary": summary,
        "written_by": "claude-sonnet",
        "references": references,
        "short": split_sections(short_md),
        "long": split_sections(long_md),
        "clinical": split_sections(clinical_md),
    }
    for key in ("short", "long", "clinical"):
        if not data[key]:
            raise ValueError(f"{key} is empty for {slug}")
    outpath = os.path.join(OUTDIR, f"{slug}.article.json")
    with open(outpath, "w") as f:
        json.dump(data, f, indent=1, ensure_ascii=False)
    print("wrote", outpath, {k: len(data[k]) for k in ("short","long","clinical")})
    return outpath
