#!/usr/bin/env python3
"""Turn a Notion "Markdown & CSV" export into a CompassDocs import zip.

Usage: python3 notion2compassdocs.py EXPORT_FOLDER SPACE_SLUG "Space name"
Needs Python 3.8+ only. Writes SPACE_SLUG-import.zip and SPACE_SLUG-checklist.csv.
Every page is imported as a draft so you can review it before publishing.
"""
import csv, json, re, sys, zipfile
from pathlib import Path
from urllib.parse import unquote

NOTION_ID = re.compile(r"\s+[0-9a-f]{32}$")  # Notion adds " <32-character id>" to every name


def clean(name):
    return NOTION_ID.sub("", name).strip()


def main(folder, space, space_name):
    root = Path(folder)
    space = re.sub(r"[^a-z0-9]+", "-", space.lower()).strip("-") or "imported"
    out, report = Path(f"{space}-import.zip"), Path(f"{space}-checklist.csv")
    seen, pages = {}, 0
    with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z, report.open("w", newline="") as r:
        todo = csv.writer(r)
        todo.writerow(["document", "what to check", "detail"])
        for page in sorted(root.rglob("*.md"), key=lambda p: (len(p.relative_to(root).parts), str(p))):
            text = page.read_text(encoding="utf-8", errors="replace").lstrip("﻿")
            lines = text.splitlines()
            # Notion starts each page with "# Title"; use it, else the file name.
            if lines and lines[0].startswith("# "):
                title, body = lines[0][2:].strip(), "\n".join(lines[1:]).lstrip("\n")
            else:
                title, body = clean(page.stem), text
            title = title or "Untitled"
            # The importer matches pages by title within a space, so keep titles unique.
            n = seen.get(title.lower(), 0) + 1
            seen[title.lower()] = n
            if n > 1:
                todo.writerow([title, "duplicate title", f"imported as \"{title} ({n})\"; rename or merge it"])
                title = f"{title} ({n})"
            parent = " / ".join(clean(p) for p in page.relative_to(root).parent.parts)
            if parent:
                todo.writerow([title, "parent page", parent])
            for src in re.findall(r"!\[[^\]]*\]\(([^)\s]+)", body):
                if not src.startswith(("http://", "https://")):
                    todo.writerow([title, "image", unquote(src)])
            for src in re.findall(r"(?<!!)\[[^\]]*\]\(([^)\s]+\.md)\)", body):
                todo.writerow([title, "link to another page", clean(Path(unquote(src)).stem)])
            front = {"title": title, "space": space, "space_name": space_name,
                     "type": "knowledge", "status": "draft", "tags": ["from-notion"]}
            head = "\n".join(f"{k}: {json.dumps(v, ensure_ascii=False)}" for k, v in front.items())
            z.writestr(f"documents/{space}/{pages:04d}.md", f"---\n{head}\n---\n\n{body}")
            pages += 1
        for table in sorted(root.rglob("*.csv")):
            todo.writerow([clean(table.stem), "database (CSV)", "not imported; rebuild as a table or a page"])
        z.writestr("manifest.json", json.dumps({"spaces": [{"slug": space, "name": space_name}]}, indent=2))
    print(f"{pages} pages -> {out}; things to check listed in {report}")


if __name__ == "__main__":
    if len(sys.argv) != 4:
        sys.exit(__doc__)
    main(*sys.argv[1:])
