#!/usr/bin/env python3
"""Turn a Confluence HTML space export into a CompassDocs import zip.

Usage: python3 confluence2compassdocs.py EXPORT_FOLDER SPACE_SLUG "Space name"
Needs Python 3.8+ and pandoc. Writes SPACE_SLUG-import.zip and SPACE_SLUG-images.csv.
Every page is imported as a draft so you can review it before publishing.
"""
import csv, html, json, re, subprocess, sys, zipfile
from html.parser import HTMLParser
from pathlib import Path


class MainContent(HTMLParser):
    """Collects the page title and the HTML inside <div id="main-content">."""

    def __init__(self):
        super().__init__(convert_charrefs=False)
        self.title, self.in_title, self.depth, self.parts = "", False, 0, []

    def handle_starttag(self, tag, attrs):
        if tag == "title":
            self.in_title = True
        if self.depth:
            self.depth += tag == "div"
            self.parts.append(self.get_starttag_text())
        elif tag == "div" and dict(attrs).get("id") == "main-content":
            self.depth = 1

    def handle_startendtag(self, tag, attrs):
        if self.depth:
            self.parts.append(self.get_starttag_text())

    def handle_endtag(self, tag):
        if tag == "title":
            self.in_title = False
        if self.depth:
            self.depth -= tag == "div"
            if self.depth:
                self.parts.append(f"</{tag}>")

    def handle_data(self, data):
        if self.in_title:
            self.title += data
        if self.depth:
            self.parts.append(data)

    def handle_entityref(self, name):
        self.handle_data(f"&{name};")

    def handle_charref(self, name):
        self.handle_data(f"&#{name};")


def main(folder, space, space_name):
    space = re.sub(r"[^a-z0-9]+", "-", space.lower()).strip("-") or "imported"
    out, report = Path(f"{space}-import.zip"), Path(f"{space}-images.csv")
    pages = 0
    with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z, report.open("w", newline="") as r:
        images = csv.writer(r)
        images.writerow(["document", "image"])
        for page in sorted(Path(folder).glob("*.html")):
            if page.name == "index.html":
                continue
            p = MainContent()
            p.feed(page.read_text(encoding="utf-8", errors="replace"))
            title = html.unescape(p.title.split(" : ", 1)[-1]).strip()
            if not title or not p.parts:
                print(f"skipped {page.name}: no title or main content")
                continue
            body = subprocess.run(
                ["pandoc", "-f", "html", "-t", "gfm-raw_html", "--wrap=none"],
                input="".join(p.parts), capture_output=True, text=True, check=True,
            ).stdout
            for src in re.findall(r"!\[[^\]]*\]\(([^)\s]+)", body):
                images.writerow([title, src])
            front = {"title": title, "space": space, "space_name": space_name,
                     "type": "knowledge", "status": "draft", "tags": ["from-confluence"]}
            head = "\n".join(f"{k}: {json.dumps(v, ensure_ascii=False)}" for k, v in front.items())
            z.writestr(f"documents/{space}/{page.stem}.md", f"---\n{head}\n---\n\n{body}")
            pages += 1
        z.writestr("manifest.json", json.dumps({"spaces": [{"slug": space, "name": space_name}]}, indent=2))
    print(f"{pages} pages -> {out}; image references listed in {report}")


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