#!/usr/bin/env python3
"""
Daily monitor for Keith's "AI Claude Refinements" Google Doc.
Fetches current content, diffs against last snapshot, writes change reports
that Daichi sees in the dashboard. Also pings via telegram bridge if available.
"""
import difflib
import hashlib
import json
import subprocess
import urllib.request
from datetime import datetime
from pathlib import Path

DOC_ID = "1rZNmoTtgQ_Ouh7WhTSgUT4mkQkFy2-Z3AAQT-zp5p8c"
EXPORT_URL = f"https://docs.google.com/document/d/{DOC_ID}/export?format=txt"

BASE = Path(__file__).parent
SNAPSHOT = BASE / "snapshot.txt"
CHANGES_LOG = BASE / "changes.log"
LATEST_DIFF = BASE / "latest_diff.md"
HISTORY_DIR = BASE / "history"
HISTORY_DIR.mkdir(exist_ok=True)


def fetch_doc() -> str:
    req = urllib.request.Request(EXPORT_URL, headers={"User-Agent": "Mozilla/5.0"})
    with urllib.request.urlopen(req, timeout=30) as r:
        raw = r.read().decode("utf-8")
    # Normalize: strip BOM, unify line endings, strip trailing whitespace per line
    raw = raw.lstrip("﻿").replace("\r\n", "\n").replace("\r", "\n")
    return "\n".join(line.rstrip() for line in raw.split("\n"))


def log(msg: str):
    line = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}\n"
    print(line, end="")
    CHANGES_LOG.write_text(CHANGES_LOG.read_text() + line if CHANGES_LOG.exists() else line)


def notify_telegram(msg: str):
    """Best effort telegram notification via bridge bot."""
    try:
        bridge = Path.home() / "claude-telegram-bridge"
        if not bridge.exists():
            return
        # Bridge has a send_message helper or we use the bot directly
        send_script = bridge / "send_notification.py"
        if send_script.exists():
            subprocess.run(
                ["python3", str(send_script), msg],
                timeout=10, capture_output=True,
            )
    except Exception:
        pass


def main():
    try:
        current = fetch_doc()
    except Exception as e:
        log(f"FETCH FAILED: {e}")
        return

    if not SNAPSHOT.exists():
        SNAPSHOT.write_text(current)
        log("baseline snapshot saved (first run)")
        return

    previous = SNAPSHOT.read_text()
    if hashlib.sha256(current.encode()).hexdigest() == hashlib.sha256(previous.encode()).hexdigest():
        log("no changes")
        return

    diff = list(difflib.unified_diff(
        previous.splitlines(keepends=True),
        current.splitlines(keepends=True),
        fromfile="previous", tofile="current", lineterm="",
    ))

    added = [l[1:].rstrip() for l in diff if l.startswith("+") and not l.startswith("+++")]
    removed = [l[1:].rstrip() for l in diff if l.startswith("-") and not l.startswith("---")]
    added = [a for a in added if a.strip()]
    removed = [r for r in removed if r.strip()]

    # Save snapshot AFTER computing diff
    ts = datetime.now().strftime("%Y-%m-%d_%H%M")
    (HISTORY_DIR / f"snapshot_{ts}.txt").write_text(previous)
    SNAPSHOT.write_text(current)

    # Write human readable change report
    report = f"""# Keith Doc Changes — {datetime.now().strftime('%Y-%m-%d %H:%M')}

Source: https://docs.google.com/document/d/{DOC_ID}/mobilebasic

## Added lines ({len(added)})

"""
    for a in added:
        report += f"+ {a}\n"
    report += f"\n## Removed lines ({len(removed)})\n\n"
    for r in removed:
        report += f"- {r}\n"
    report += f"\n## Raw diff\n\n```diff\n{''.join(diff)}\n```\n"

    LATEST_DIFF.write_text(report)
    log(f"CHANGES DETECTED: +{len(added)} -{len(removed)} lines | saved diff to {LATEST_DIFF}")

    summary = f"keith doc updated: +{len(added)} -{len(removed)} lines. see {LATEST_DIFF.name}"
    notify_telegram(summary)


if __name__ == "__main__":
    main()
