#!/usr/bin/env python3
"""Summarize all Discord channel histories using Haiku."""
import json, os, sys, time, subprocess

API_KEY = os.environ.get("ANTHROPIC_API_KEY")
MODEL = "claude-haiku-4-5-20251001"

def call_haiku(prompt, max_tokens=1500):
    import urllib.request
    body = json.dumps({
        "model": MODEL,
        "max_tokens": max_tokens,
        "messages": [{"role": "user", "content": prompt}]
    }).encode()
    req = urllib.request.Request(
        "https://api.anthropic.com/v1/messages",
        data=body,
        headers={
            "content-type": "application/json",
            "x-api-key": API_KEY,
            "anthropic-version": "2023-06-01"
        }
    )
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            data = json.loads(resp.read())
            return data["content"][0]["text"]
    except Exception as e:
        return f"Error: {e}"

def extract_messages(json_path, max_msgs=200):
    with open(json_path) as f:
        data = json.load(f)
    messages = data.get("messages", [])
    channel = data.get("channel", {})
    guild = data.get("guild", {}).get("name", "Unknown")
    ch_name = channel.get("name", "unknown")
    category = channel.get("category", "")

    lines = []
    for msg in messages[:max_msgs]:
        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)
        if not content:
            continue
        bot = " (bot)" if is_bot else ""
        lines.append(f"{author}{bot} ({ts}): {content[:500]}")

    return {
        "guild": guild,
        "channel": ch_name,
        "category": category,
        "total_msgs": len(messages),
        "conversation": "\n".join(lines)[:15000]
    }

def summarize_channel(info):
    if not info["conversation"].strip():
        return None

    prompt = f"""Summarize this Discord channel conversation from a creative agency called Curious Endeavor (CE).

Guild: {info['guild']}
Channel: #{info['channel']}
Category: {info['category']}
Total messages: {info['total_msgs']}

Conversation:
{info['conversation']}

Write a concise summary with these sections:
## Overview
One paragraph: what this channel is about and its purpose.

## Key Decisions & Outcomes
Bullet points of important decisions made, deliverables completed, or outcomes reached.

## Active/Open Items
Any unresolved questions, pending work, or next steps mentioned.

## Key Links & References
Any important URLs, documents, or files mentioned.

Keep it concise and actionable. Focus on what matters for someone picking up this project."""

    return call_haiku(prompt)

def main():
    guilds = {
        "ce-lite": "/root/ce-channels-ce-lite",
        "olevia": "/root/ce-channels-olevia",
        "spoken": "/root/ce-channels-spoken",
        "white-space": "/root/ce-channels-white-space",
        "ce-main": "/root/ce-channels",
    }

    output_dir = "/tmp/channel-summaries"
    os.makedirs(output_dir, exist_ok=True)

    total = 0
    for guild_key, guild_path in guilds.items():
        if not os.path.exists(guild_path):
            continue
        for ch in sorted(os.listdir(guild_path)):
            ch_path = os.path.join(guild_path, ch)
            if not os.path.isdir(ch_path):
                continue

            # Find history file
            json_file = os.path.join(ch_path, "history.json")
            md_file = os.path.join(ch_path, "discord-history.md")

            if os.path.exists(json_file):
                info = extract_messages(json_file)
            elif os.path.exists(md_file):
                # For CE main guild (markdown format)
                with open(md_file) as f:
                    content = f.read()[:15000]
                info = {
                    "guild": "Curious Endeavor",
                    "channel": ch,
                    "category": "",
                    "total_msgs": content.count("**"),
                    "conversation": content
                }
            else:
                continue

            if not info["conversation"].strip():
                continue

            out_file = os.path.join(output_dir, f"{guild_key}--{ch}.md")

            # Skip if already done
            if os.path.exists(out_file):
                print(f"SKIP {guild_key}/{ch}")
                continue

            print(f"SUMMARIZING {guild_key}/{ch} ({info['total_msgs']} msgs)...", end=" ", flush=True)
            summary = summarize_channel(info)

            if summary:
                with open(out_file, "w") as f:
                    f.write(summary)
                print(f"OK ({len(summary)} chars)")
            else:
                print("EMPTY")

            total += 1
            time.sleep(0.3)  # Rate limit buffer

    print(f"\nDone! {total} channels summarized.")
    print(f"Output: {output_dir}/")

if __name__ == "__main__":
    main()
