#!/usr/bin/env python3
"""Extract readable conversation history from Discord JSON exports."""
import json, sys, os

def extract_channel(json_path, max_chars=80000):
    with open(json_path) as f:
        data = json.load(f)

    channel = data.get("channel", {})
    messages = data.get("messages", [])

    if not messages:
        return None

    lines = []
    for msg in messages:
        author = msg.get("author", {}).get("nickname") or msg.get("author", {}).get("name", "?")
        content = msg.get("content", "").strip()
        ts = msg.get("timestamp", "")[:10]
        is_bot = msg.get("author", {}).get("isBot", False)

        # Skip empty messages
        if not content and not msg.get("attachments"):
            continue

        # Format attachments
        attachments = []
        for att in msg.get("attachments", []):
            attachments.append(f"[{att.get('fileName', 'file')}]")

        att_str = " " + " ".join(attachments) if attachments else ""

        bot_marker = " 🤖" if is_bot else ""
        line = f"**{author}**{bot_marker} ({ts}): {content}{att_str}"
        lines.append(line)

    result = "\n\n".join(lines)
    if len(result) > max_chars:
        result = result[:max_chars] + "\n\n... (truncated)"

    return result

def main():
    guild_dir = sys.argv[1]
    for channel_dir in sorted(os.listdir(guild_dir)):
        full_path = os.path.join(guild_dir, channel_dir)
        if not os.path.isdir(full_path):
            continue

        json_file = os.path.join(full_path, "history.json")
        if not os.path.exists(json_file):
            continue

        history = extract_channel(json_file, max_chars=60000)
        if not history:
            continue

        # Write to a temp file per channel
        out_path = f"/tmp/notion-history-{channel_dir}.md"
        with open(out_path, "w") as f:
            f.write(history)

        msg_count = history.count("**")
        print(f"{channel_dir}|{msg_count}|{out_path}")

if __name__ == "__main__":
    main()
