"""
Pradhya · NanoClaw Workshop · Unit 08
======================================

A scheduled daily briefing skill that reads:
    - your calendar (today + tomorrow)
    - the wiki (open commitments)
    - any inbox / message-queue you wire in

… and sends a single message to your phone every morning.

This is the killer use case our example user, Avery Stone, runs. The point
is not the AI — it is the *consistency*. A briefing every morning, at
the same time, that is grounded in your actual context.

This file is deliberately a *stub* — you fill in the connectors that
match your stack. The shape is what teaches.

Schedule with cron:
    0 6 * * *  cd /home/you/nanoclaw && .venv/bin/python daily_briefing.py
"""

from __future__ import annotations

import datetime as dt
import os
import sys

from anthropic import Anthropic

from nanoclaw_demo import index_text, read_wiki_page

MODEL = "claude-sonnet-4-6"
client = Anthropic()


# ---------------------------------------------------------------------
# Connectors — replace these with your real ones
# ---------------------------------------------------------------------
def calendar_events(date: dt.date) -> str:
    """Return a string summary of events for `date`.
    Wire to Google Calendar, Apple Calendar, or your real source."""
    # TODO: replace with real calendar API.
    return "(no calendar connector configured)"


def wiki_open_threads() -> str:
    """Ask the wiki for outstanding commitments. Uses the model + the index."""
    resp = client.messages.create(
        model=MODEL,
        max_tokens=600,
        system="You list outstanding commitments from the user's wiki. "
               "Format: dash bullets, deadline first, then commitment. "
               "Max 10 items. Skip resolved threads.",
        messages=[
            {"role": "user", "content":
                "Outstanding commitments. Wiki index below:\n\n" + index_text()}
        ],
    )
    return resp.content[0].text


def send_to_self(text: str) -> None:
    """Send the briefing to your default channel.
    Wire to Telegram, Pushover, email, etc."""
    print("=" * 60)
    print(text)
    print("=" * 60)


# ---------------------------------------------------------------------
# The briefing
# ---------------------------------------------------------------------
SYSTEM = """You produce a morning briefing for a busy professional.

Format the briefing in three sections, in this order:

  TODAY      — events today, key meetings, the one thing that must move
  THE WATCH  — open threads with deadlines, ranked
  THE PREP   — the single biggest prep task for the next 24 hours

Rules:
- Max 250 words total.
- No preamble. No greetings.
- Specific names, deadlines, decisions. Skip filler.
- If a thread is older than 6 weeks with no activity, drop it.
- Surface anything I committed to that hasn't appeared in any system."""


def compose_briefing() -> str:
    today    = dt.date.today()
    tomorrow = today + dt.timedelta(days=1)

    events_today    = calendar_events(today)
    events_tomorrow = calendar_events(tomorrow)
    open_threads    = wiki_open_threads()

    user = f"""Today: {today.isoformat()} ({today.strftime('%A')}).

CALENDAR TODAY:
{events_today}

CALENDAR TOMORROW (preview):
{events_tomorrow}

OPEN THREADS:
{open_threads}

Write the briefing now."""

    resp = client.messages.create(
        model=MODEL,
        max_tokens=600,
        system=SYSTEM,
        messages=[{"role": "user", "content": user}],
    )
    return resp.content[0].text


def main() -> None:
    if not os.environ.get("ANTHROPIC_API_KEY"):
        sys.exit("ANTHROPIC_API_KEY is not set.")
    text = compose_briefing()
    send_to_self(text)


if __name__ == "__main__":
    main()
