#!/usr/bin/env python3
"""Daily summary script — generates and sends Harvey's daily summary to Mike via Telegram."""
import json
import os
import sys
import urllib.request
import urllib.parse
from datetime import date
from pathlib import Path

WORKSPACE = Path(os.path.expanduser("~/.openclaw/workspace"))
SECRETS_DIR = Path(os.path.expanduser("~/.openclaw/secrets"))
TELEGRAM_TOKEN = "7764678817:AAH1_A4woI2gKd13gSfRF_uAStowKxsKARg"
MIKE_CHAT_ID = "8792051045"
TODAY = date.today().isoformat()


def read_file_safe(path):
    try:
        return Path(path).read_text()
    except Exception:
        return ""


def get_anthropic_key():
    key_file = SECRETS_DIR / "anthropic-api-key.txt"
    if key_file.exists():
        return key_file.read_text().strip()
    return os.environ.get("ANTHROPIC_API_KEY", "")


def gather_context():
    parts = []

    # Today's daily notes
    daily = WORKSPACE / "memory" / f"{TODAY}.md"
    content = read_file_safe(daily)
    if content:
        parts.append(f"=== TODAY'S DAILY NOTES ({TODAY}) ===\n{content}")
    else:
        parts.append(f"=== TODAY'S DAILY NOTES ===\n(no notes file for {TODAY})")

    # Channel memory files
    channels_dir = WORKSPACE / "memory" / "channels"
    if channels_dir.exists():
        for ch_file in sorted(channels_dir.glob("*.md")):
            ch_content = read_file_safe(ch_file)
            if ch_content:
                parts.append(f"=== CHANNEL: {ch_file.stem} ===\n{ch_content}")

    # projects.md
    projects = WORKSPACE / "memory" / "projects.md"
    content = read_file_safe(projects)
    if content:
        parts.append(f"=== PROJECTS ===\n{content}")

    return "\n\n".join(parts)


def call_anthropic(api_key, context):
    url = "https://api.anthropic.com/v1/messages"
    prompt = f"""You are Harvey, Mike's AI assistant. Based on the context below, generate a clean daily summary.

Format it EXACTLY like this (use these exact emoji headers):

📋 Harvey Daily Summary — {TODAY}

🔧 What I worked on:
• [bullet points of tasks/work done today]

💬 Conversations:
• [channel name: brief topic summary, one line each]

✅ TODOs updated:
• [any new or completed todos mentioned today]

⚠️ Needs your attention:
• [open questions, items needing Mike's input, anything unresolved]

Keep it concise — this is a Telegram message. Bullets only, no long paragraphs.

CONTEXT:
{context}"""

    payload = json.dumps({
        "model": "claude-opus-4-6",
        "max_tokens": 1024,
        "messages": [{"role": "user", "content": prompt}]
    }).encode()

    req = urllib.request.Request(
        url,
        data=payload,
        headers={
            "Content-Type": "application/json",
            "x-api-key": api_key,
            "anthropic-version": "2023-06-01"
        }
    )
    with urllib.request.urlopen(req) as resp:
        data = json.loads(resp.read())
    return data["content"][0]["text"]


def send_telegram(text):
    url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
    payload = json.dumps({
        "chat_id": MIKE_CHAT_ID,
        "text": text,
        "parse_mode": "Markdown"
    }).encode()
    req = urllib.request.Request(url, data=payload, headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req) as resp:
        return json.loads(resp.read())


def save_summary(text):
    summaries_dir = WORKSPACE / "memory" / "summaries"
    summaries_dir.mkdir(parents=True, exist_ok=True)
    out_file = summaries_dir / f"{TODAY}.md"
    out_file.write_text(text)
    print(f"[saved] {out_file}")


def main():
    print(f"[daily-summary] Generating summary for {TODAY}...")

    api_key = get_anthropic_key()
    if not api_key:
        print("ERROR: No Anthropic API key found", file=sys.stderr)
        sys.exit(1)

    context = gather_context()
    print(f"[daily-summary] Gathered {len(context)} chars of context")

    summary = call_anthropic(api_key, context)
    print(f"[daily-summary] Generated summary ({len(summary)} chars)")

    save_summary(summary)

    result = send_telegram(summary)
    if result.get("ok"):
        print(f"[daily-summary] Sent to Mike via Telegram (message_id: {result['result']['message_id']})")
    else:
        print(f"[daily-summary] Telegram delivery failed: {result}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
