#!/usr/bin/env python3
"""Load the markdown articles in content/blog into the blog_post table.

    python3 content/import_blog.py            import as drafts
    python3 content/import_blog.py --publish  import and publish immediately

Re-running updates existing posts by slug rather than duplicating them.
"""
import os, re, sys, json
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "server"))
import db  # noqa: E402

BLOG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "blog")


def parse(path):
    text = open(path, encoding="utf-8").read()
    m = re.match(r"^---\n(.*?)\n---\n(.*)$", text, re.S)
    if not m:
        return None
    meta = {}
    for line in m.group(1).splitlines():
        if ":" not in line:
            continue
        k, v = line.split(":", 1)
        meta[k.strip()] = v.strip().strip('"')
    body = m.group(2).strip()

    faqs = []
    fm = re.search(r"## Frequently asked\n(.*?)(?:\n---|\Z)", body, re.S)
    if fm:
        for q, a in re.findall(r"\*\*(.+?)\*\*\s*(.+?)(?=\n\n\*\*|\Z)", fm.group(1), re.S):
            faqs.append((q.strip(), " ".join(a.split())))
    return meta, body, faqs


def main(publish=False):
    db.init_db()
    cats = {c["slug"]: c["id"] for c in db.query("SELECT id, slug FROM blog_category")}
    n_new = n_upd = 0
    for fn in sorted(os.listdir(BLOG_DIR)):
        if not fn.endswith(".md"):
            continue
        parsed = parse(os.path.join(BLOG_DIR, fn))
        if not parsed:
            print(f"  skipped {fn} (no frontmatter)")
            continue
        meta, body, faqs = parsed
        slug = meta.get("slug")
        words = len(body.split())
        existing = db.query("SELECT id FROM blog_post WHERE slug = ?", (slug,), one=True)
        args = (meta.get("title"), meta.get("h1"), meta.get("meta_description"),
                meta.get("focus_keyword"), meta.get("secondary_keywords"),
                cats.get(meta.get("category")), body, max(1, words // 220),
                "published" if publish else meta.get("status", "draft"),
                db.now_iso() if publish else None, db.now_iso(),
                meta.get("schema_type", "Article"), meta.get("review_due_on"))
        if existing:
            db.execute(
                "UPDATE blog_post SET title=?, h1=?, meta_description=?, focus_keyword=?,"
                " secondary_keywords=?, category_id=?, body_md=?, reading_minutes=?, status=?,"
                " published_at=COALESCE(?, published_at), updated_at=?, schema_type=?, review_due_on=?"
                " WHERE slug=?", args + (slug,))
            pid = existing["id"]
            db.execute("DELETE FROM blog_faq WHERE post_id = ?", (pid,))
            n_upd += 1
        else:
            pid = db.execute(
                "INSERT INTO blog_post (title, h1, meta_description, focus_keyword, secondary_keywords,"
                " category_id, body_md, reading_minutes, status, published_at, updated_at, schema_type,"
                " review_due_on, slug) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", args + (slug,))
            n_new += 1
        for i, (q, a) in enumerate(faqs):
            db.execute("INSERT INTO blog_faq (post_id, question, answer, sort_order) VALUES (?,?,?,?)",
                       (pid, q, a, i))
        print(f"  {slug}  ({words} words, {len(faqs)} FAQ entries)")
    print(f"\n{n_new} new, {n_upd} updated. Status: {'published' if publish else 'draft'}.")


if __name__ == "__main__":
    main("--publish" in sys.argv)
