#!/usr/bin/env python3
"""
Tägliches Claude/Anthropic News Briefing
Sendet jeden Morgen eine Zusammenfassung an Telegram.

Cron: 0 7 * * * /root/aria/scripts/claude-news-daily.py
"""

import os
import json
import re
import urllib.request
import urllib.parse
from datetime import datetime, timezone

# ── Config ────────────────────────────────────────────────────────────────────
def load_env():
    env = {}
    for path in ['/root/aria/.env', '/root/aria/.env']:
        try:
            for line in open(path):
                line = line.strip()
                if '=' in line and not line.startswith('#'):
                    k, v = line.split('=', 1)
                    env[k.strip()] = v.strip().strip('"\'')
        except FileNotFoundError:
            pass
    return env

ENV = load_env()
BOT_TOKEN = ENV.get('TELEGRAM_BOT_TOKEN', '')
CHAT_ID = ENV.get('TELEGRAM_CHAT_ID', '${TELEGRAM_CHAT_ID}')
ANTHROPIC_KEY = ENV.get('ANTHROPIC_API_KEY', '')

# ── Fetchers ──────────────────────────────────────────────────────────────────

def fetch(url: str, timeout: int = 15) -> str:
    req = urllib.request.Request(url, headers={
        'User-Agent': 'Mozilla/5.0 (compatible; AriaBot/1.0)',
        'Accept': 'text/html,application/json,*/*',
    })
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.read().decode('utf-8', errors='replace')
    except Exception as e:
        return f"[fetch error: {e}]"


def fetch_github_releases() -> list[dict]:
    raw = fetch('https://api.github.com/repos/anthropics/claude-code/releases?per_page=5')
    try:
        releases = json.loads(raw)
        result = []
        for r in releases[:3]:
            body = r.get('body', '') or ''
            # Strip markdown noise
            body = re.sub(r'!\[.*?\]\(.*?\)', '', body)
            body = re.sub(r'\[.*?\]\(.*?\)', lambda m: m.group(0).split('(')[0].strip('[]'), body)
            body = body.strip()[:600]
            result.append({
                'tag': r.get('tag_name', ''),
                'name': r.get('name', '') or r.get('tag_name', ''),
                'date': r.get('published_at', '')[:10],
                'body': body,
            })
        return result
    except Exception:
        return []


def extract_anthropic_news(html: str) -> list[str]:
    """Extract recent article titles/descriptions from Anthropic news page."""
    items = []
    # Look for article headings
    patterns = [
        r'<h[23][^>]*>([^<]{20,200})</h[23]>',
        r'"headline"\s*:\s*"([^"]{20,200})"',
        r'<title>([^<]{10,100})</title>',
    ]
    seen = set()
    for pat in patterns:
        for m in re.finditer(pat, html, re.IGNORECASE):
            title = re.sub(r'\s+', ' ', m.group(1)).strip()
            if title and title not in seen and 'anthropic' not in title.lower()[:15]:
                seen.add(title)
                items.append(title)
        if len(items) >= 5:
            break
    return items[:5]


def extract_changelog(html: str) -> list[str]:
    """Extract recent changelog entries."""
    items = []
    # Changelog entries often start with date headers or version numbers
    patterns = [
        r'<h[234][^>]*>((?:20\d\d|v\d|\w+ \d{4})[^<]{0,150})</h[234]>',
        r'##\s+([^\n]{10,100})',
    ]
    seen = set()
    for pat in patterns:
        for m in re.finditer(pat, html, re.IGNORECASE):
            entry = re.sub(r'\s+', ' ', m.group(1)).strip()
            if entry not in seen:
                seen.add(entry)
                items.append(entry)
    return items[:5]


# ── Claude Summarizer ─────────────────────────────────────────────────────────

def extract_release_highlights(body: str) -> list[str]:
    """Extract bullet points from GitHub release markdown."""
    if not body:
        return []
    lines = body.split('\n')
    bullets = []
    for line in lines:
        line = line.strip()
        # Bullet points and list items
        if re.match(r'^[-*•]\s+', line):
            item = re.sub(r'^[-*•]\s+', '', line).strip()
            item = re.sub(r'`([^`]+)`', r'\1', item)  # remove backticks
            item = re.sub(r'\*\*([^*]+)\*\*', r'\1', item)  # remove bold
            if len(item) > 10:
                bullets.append(item[:120])
        elif re.match(r'^\d+\.\s+', line):
            item = re.sub(r'^\d+\.\s+', '', line).strip()
            if len(item) > 10:
                bullets.append(item[:120])
    return bullets[:5]


def summarize_in_german(raw_content: str) -> str:
    """Use claude -p (headless) to produce a German summary."""
    import subprocess

    prompt = (
        "Du bist Aria. Fasse diese Claude/Anthropic-News in 3-5 deutschen Bulletpoints zusammen. "
        "Fokus: was ist neu, was bedeutet es praktisch. Kein Jargon. Kurz.\n\n"
        + raw_content
    )

    try:
        result = subprocess.run(
            ['claude', '-p', prompt],
            capture_output=True, text=True, timeout=45
        )
        if result.returncode == 0 and result.stdout.strip():
            return result.stdout.strip()
    except Exception:
        pass
    return None


def build_summary(releases: list[dict], news_titles: list[str]) -> str:
    """Build a German summary using claude -p for translation."""

    # Collect raw content
    raw_parts = []

    if releases:
        latest = releases[0]
        raw_parts.append(f"Claude Code {latest['tag']} ({latest['date']}): {latest['name']}")
        highlights = extract_release_highlights(latest['body'])
        for h in highlights[:5]:
            raw_parts.append(f"- {h}")
        for r in releases[1:2]:
            raw_parts.append(f"Vorherige Version: {r['tag']} ({r['date']})")

    if news_titles:
        raw_parts.append("Anthropic News:")
        for t in news_titles[:3]:
            raw_parts.append(f"- {t}")

    if not raw_parts:
        return "Keine neuen Meldungen heute."

    raw_content = '\n'.join(raw_parts)

    # Try German summarization via claude -p
    german = summarize_in_german(raw_content)
    if german:
        return german

    # Fallback: formatted English content with German headers
    sections = []
    if releases:
        latest = releases[0]
        highlights = extract_release_highlights(latest['body'])
        sections.append(f"🔧 <b>Claude Code {latest['tag']}</b> ({latest['date']})")
        for h in (highlights or [f"{latest['name']}"])[:4]:
            sections.append(f"  • {h}")
    if news_titles:
        sections.append("\n📰 <b>Anthropic News:</b>")
        for t in news_titles[:3]:
            sections.append(f"  • {t}")
    return '\n'.join(sections)


# ── Telegram ──────────────────────────────────────────────────────────────────

def send_telegram(text: str) -> bool:
    if not BOT_TOKEN:
        print("No BOT_TOKEN")
        return False

    data = urllib.parse.urlencode({
        'chat_id': CHAT_ID,
        'text': text,
        'parse_mode': 'HTML',
        'disable_web_page_preview': 'true',
    }).encode('utf-8')

    req = urllib.request.Request(
        f'https://api.telegram.org/bot{BOT_TOKEN}/sendMessage',
        data=data
    )
    try:
        with urllib.request.urlopen(req, timeout=10) as r:
            result = json.loads(r.read())
            return result.get('ok', False)
    except Exception as e:
        print(f"Telegram error: {e}")
        return False


# ── Main ──────────────────────────────────────────────────────────────────────

def main():
    print(f"[{datetime.now(timezone.utc).isoformat()}] Claude News Daily starting...")

    # Fetch all sources
    print("Fetching GitHub releases...")
    releases = fetch_github_releases()

    print("Fetching Anthropic news...")
    news_html = fetch('https://anthropic.com/news')
    news_titles = extract_anthropic_news(news_html)

    print("Fetching Claude changelog...")
    changelog_html = fetch('https://docs.anthropic.com/en/docs/about-claude/changelog')
    changelog_entries = extract_changelog(changelog_html)

    print(f"Found: {len(releases)} releases, {len(news_titles)} news, {len(changelog_entries)} changelog")

    # Build summary
    print("Building summary...")
    summary = build_summary(releases, news_titles)

    # Format message
    today = datetime.now().strftime('%d.%m.%Y')

    message = f"""🤖 <b>Claude Briefing — {today}</b>

{summary}

<i><a href="https://anthropic.com/news">Anthropic News</a> · <a href="https://docs.anthropic.com/en/docs/about-claude/changelog">Changelog</a> · <a href="https://github.com/anthropics/claude-code/releases">GitHub Releases</a></i>"""

    print("Sending to Telegram...")
    ok = send_telegram(message)
    print(f"Done. Telegram: {'OK' if ok else 'FAILED'}")


if __name__ == '__main__':
    main()
