#!/usr/bin/python3
# link_export.py: write the Mac app's conversations in a portable, iOS-importable schema so the
# iPhone RecapMuse app can show the same meetings. The Mac side of the link (see LINK-IOS.md).
#
# Reads the organizer's diary.json (engine/organize.py output) and emits epiphani-conversations.json
# in schema "epiphani.conversations/v1" — a strict superset of the iOS export doc. Write-only; never
# deletes anything. Defaults to an iCloud Drive folder visible on the iPhone in Files.
#
#   link_export.py [--rec-dir DIR] [--out DIR] [--json]
#     --rec-dir  where recordings + diary.json live (default ~/Recordings/Epiphani)
#     --out      shared folder to write into (default iCloud Drive Epiphani; created if missing)
#     --json     print the interchange JSON to stdout instead of writing a file
#
# Pure stdlib.
import sys, os, json, socket

HOME = os.path.expanduser("~")
DEFAULT_REC = os.path.join(HOME, "Recordings/Epiphani")
ICLOUD = os.path.join(HOME, "Library/Mobile Documents/com~apple~CloudDocs/Epiphani")


def load_diary(rec_dir):
    p = os.path.join(rec_dir, "diary.json")
    try:
        with open(p, encoding="utf-8") as f:
            return json.load(f)
    except (OSError, ValueError):
        return None


def to_v1(diary):
    """Map organize.py's day/conversation/clip shape into the portable v1 conversation list."""
    conversations = []
    for day in (diary or {}).get("days", []):
        for cv in day.get("conversations", []):
            blocks = []
            for c in cv.get("clips", []):
                blocks.append({
                    "time": c.get("time", ""),
                    "start": c.get("start"),
                    "end": c.get("end"),
                    "text": c.get("title", ""),      # Mac stores per-clip title; transcript text when available
                    "speaker": c.get("speaker"),
                })
            conversations.append({
                "id": cv.get("id") or (cv.get("time_range", "") + "|" + cv.get("title", "")),
                "title": cv.get("title", ""),
                "start": cv.get("start") or cv.get("time_range", ""),
                "end": cv.get("end", ""),
                "who_with": cv.get("who_with", ""),
                "summary": cv.get("summary", ""),
                "action_items": cv.get("action_items", []),
                "category": cv.get("category", ""),
                "blocks": blocks,
            })
    return conversations


def build(rec_dir):
    diary = load_diary(rec_dir)
    return {
        "schema": "epiphani.conversations/v1",
        "source_device": socket.gethostname(),
        "source_app": "RecapMuse (Mac)",
        "has_diary": diary is not None,
        "conversations": to_v1(diary),
    }


def main(argv):
    rec_dir = DEFAULT_REC
    out_dir = ICLOUD
    if "--rec-dir" in argv:
        i = argv.index("--rec-dir"); rec_dir = os.path.expanduser(argv[i + 1]) if i + 1 < len(argv) else rec_dir
    if "--out" in argv:
        i = argv.index("--out"); out_dir = os.path.expanduser(argv[i + 1]) if i + 1 < len(argv) else out_dir
    payload = build(rec_dir)
    if "--json" in argv:
        sys.stdout.write(json.dumps(payload))
        return
    try:
        os.makedirs(out_dir, exist_ok=True)
        out_path = os.path.join(out_dir, "epiphani-conversations.json")
        with open(out_path, "w", encoding="utf-8") as f:
            json.dump(payload, f, ensure_ascii=False, indent=2)
        sys.stdout.write(json.dumps({"ok": True, "wrote": out_path,
                                     "conversations": len(payload["conversations"])}))
    except OSError as e:
        sys.stdout.write(json.dumps({"ok": False, "error": str(e)[:200]}))


if __name__ == "__main__":
    main(sys.argv[1:])
