Skip to content

AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).

77.4 KB
Raw Blame
"""Act as me: the caller's own delegation settings and "How I write".

Every route is about the CALLER'S OWN delegation — a person turns it on and
edits their writing profile for themselves; nobody does it for anyone else —
and only for a caller ``delegation.settings.can_delegate`` allows (the
principal, and team members once the owner lets them). Anyone else gets 403
``not_available_yet``, so the Settings card hides itself.

A request with no ``x-caller-email`` is not a sign-in: it would resolve to the
principal (the CLI / curl rule in ``chat._resolve_caller_person_id``), but a
setting that lets the Executive write in someone's name needs the person
themselves. Such a request is refused (403 ``sign_in_required``) unless the
API runs under local login (``make dev``, never on a public deployment). The
header is stamped by the UI proxy from the Google sign-in; whoever holds
``BACKEND_SHARED_SECRET`` is trusted as that proxy, as on every principal-only
route.

Routes:
  GET    /delegation              — on/off, the Gmail connection and the inbox
                                    watcher's switch and health
  PUT    /delegation              — {enabled}; turning it on needs the caller's
                                    own Gmail connected (409 otherwise); turning
                                    it off turns the inbox watcher and Read my
                                    calendar off too
  PUT    /delegation/calendar     — {enabled}: Read my calendar
                                    (delegation.calendar); on needs Act as me
                                    on and a calendar read that works (409
                                    calendar_not_granted when their sign-in
                                    lacks it, 503 when it can't be reached)
  PUT    /delegation/reach        — {step}: How far it goes as you, one dial
                                    over Act as me, the inbox watcher, Handle
                                    it for me and its level, and Everything
                                    (off, when_asked, inbox, careful,
                                    balanced, bold, everything). Down turns
                                    the higher switches off; up turns each on
                                    through its own route and its checks
  PUT    /delegation/inbox        — {enabled?, mailbox_drafts?}: "Draft
                                    replies to my inbox"; turning it on needs
                                    Act as me on and Gmail connected (409),
                                    and starts from now. mailbox_drafts: also
                                    save each reply in their Drafts (off by
                                    default: on its card alone)
  POST   /delegation/inbox/check  — check the inbox now (202; 409 when the
                                    switch is off or a check is running)
  GET    /delegation/replies      — the reply cards waiting for the caller
                                    (from the database; no Gmail call)
  POST   /delegation/drafts/{id}/send — {thread_moved_on?}: send a draft
                                    chat wrote as the caller, on their tap,
                                    exactly as written (their own only; 404
                                    otherwise). Needs a caller the API knows
                                    is that person, like a card's Send (409
                                    ``caller_signing_required``); 409
                                    ``confirm`` asks a second yes when the
                                    conversation moved on, and
                                    ``draft_changed`` when it was edited in
                                    the mailbox
  PUT    /delegation/replies/{id}/text — {text}: change a reply's words
  PUT    /delegation/replies/{id}/recipients — {everyone}: the sender only,
         or everyone the email went to
                                    before Send, on its card and in their
                                    Drafts when it is there too. Needs a
                                    caller the API knows is that person, like
                                    Send (delegation.card_drafts)
  POST   /delegation/replies/{id}/answer — {answers: [{question_index,
                                    answer_text}]}: answer what the reply
                                    left to decide; one model call rewrites
                                    the draft with it, saved like the text
                                    route (same checks); returns the card
                                    with changed_sentences. 429 past the
                                    hourly limit (delegation.answers)
  POST   /delegation/replies/{id}/change — {text}: what to change, in the
                                    caller's words; rewritten and saved like
                                    an answer (same checks and limit); the
                                    request and the Executive's line on what
                                    it changed join the card's conversation
  PUT    /delegation/handle-it    — {enabled?, mode?}: Handle it for me,
                                    the inbox watcher sending some replies on
                                    its own, mode careful | balanced | bold
                                    (delegation.handle_it). Needs a
                                    caller the API knows is that person
                                    (signed sign-ins, or local login: 403 /
                                    409 ``caller_signing_required``), and
                                    turning it on needs Draft replies to my
                                    inbox on (409). Turning the inbox watcher
                                    off turns it off too
  PUT    /delegation/training     — {replies?, follow_ups?, actions?, drafts?,
                                    actions_on?}: put Act as me's settings in
                                    or out of training, or Suggested actions
                                    On (delegation.training). Needs a
                                    caller the API knows is that person, but
                                    for a change that only holds more back
  DELETE /delegation/learned/{id} — forget one thing it learned in training
                                    (the "on its own next time" tick on a
                                    card, or an example). The caller's own only
  PUT    /delegation/take-the-lead — {enabled}: Take the lead as you, the
                                    owner's alone for now: Handle it for
                                    me's setting gives way to the added rules
                                    (orchestrator.take_the_lead); turning it
                                    on turns Handle it for me on
  GET|POST /delegation/take-the-lead/rules, DELETE …/rules/{id}
                                  — the caller's own rules for it (removing
                                    one needs the same provable caller)
  GET    /delegation/invites      — the meeting invite cards waiting for the
                                    caller (delegation.invites; from the
                                    database, no calendar call). Accept and
                                    Decline are POST /decisions/{id}/approve
                                    with edits.answer
  GET    /delegation/handled      — the caller's replies sent on its own in
                                    the last 7 days, with the questions each
                                    left for them, and the invites it
                                    accepted on its own (source "invite",
                                    with a one-line summary)
  GET    /delegation/voice        — "How I write"
  POST   /delegation/voice/learn  — learn it from the caller's sent mail (409
                                    in_progress / locked / too_soon /
                                    not_enough_mail / no_profile / changed)
  POST   /delegation/voice/signature — take the signature from the caller's
                                    Gmail settings again (a locked profile
                                    stays locked; nothing else changes)
  POST   /delegation/voice/describe — {description}: write the style from
                                    the caller's own words, applied to what
                                    they have, plus a sample reply; saves
                                    nothing (they save it with PUT). 409
                                    empty / too_long / in_progress /
                                    too_many / no_profile
  PUT    /delegation/voice        — edit fields, lock / unlock
  DELETE /delegation/voice        — forget it (history kept)
  PUT    /delegation/team         — {enabled}: the owner's "Let team members
                                    use Act as me" (principal only; 409
                                    ``not_available`` unless the install
                                    allows it, ``DELEGATION_TEAM_MEMBERS``)

``GET /delegation`` gives the principal ``team`` while the install allows it:
the switch and, for each team member who has it on, counts only — drafts
saved and sent in the last 30 days, never what they said or to whom. A team
member's own mail, cards and rows are theirs alone.

Every change writes a private audit row.
"""
from __future__ import annotations

import asyncio
import logging
from dataclasses import asdict
from typing import Any, Literal

from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, ConfigDict, Field

from openexecutive.api import caller as api_caller
from openexecutive.delegation.gmail import (
    BLOCKING_CODES,
    STATUS_MESSAGES,
    GmailAuthError,
    GmailError,
    credential_provider,
    gmail_for,
    gmail_status,
)
from openexecutive.delegation.settings import (
    can_delegate,
    enabled_person_ids,
    is_enabled,
    local_login,
    set_enabled,
    set_team_members,
    team_members_available,
    team_members_switch,
)
from openexecutive.delegation.voice import (
    DESCRIPTION_MAX_CHARS,
    StoredVoice,
    VoiceError,
    describe_voice,
    get_voice,
    learn_from_sent_mail,
    reset_voice,
    save_voice,
    validate_profile,
)
from openexecutive.people.models import Person

router = APIRouter()
logger = logging.getLogger(__name__)

# Gmail status -> the 409 code a caller gets when it blocks turning it on.
_BLOCKING_CODES = BLOCKING_CODES


class GmailConnection(BaseModel):
    status: str
    message: str
    email: str | None = None
    # The commands that connect this caller's own Gmail or Outlook (there is
    # no OAuth callback: the token is minted locally, like the Executive's own).
    connect_command: str
    outlook_connect_command: str = ""
    # Which mailbox the saved sign-in opens: "google" or "microsoft".
    provider: str = "google"


class InboxOut(BaseModel):
    enabled: bool
    status: str
    message: str
    watch_since: str | None = None
    last_poll_at: str | None = None
    checking: bool = False
    # Also save each reply in their mailbox's Drafts (off: on its card alone).
    mailbox_drafts: bool = False


class TeamMemberUse(BaseModel):
    """One team member's use of Act as me, as the owner sees it: counts only."""

    person_id: int
    name: str
    enabled: bool
    inbox: bool
    drafts_30d: int
    sent_30d: int


class TeamOut(BaseModel):
    enabled: bool
    members: list[TeamMemberUse]


class LearnedOut(BaseModel):
    id: int
    label: str
    # The setting it was learned under: replies, follow_ups, actions or drafts.
    setting: str
    # What they sent after changing a draft, kept as an example ("").
    example: str
    uses: int
    created_at: str


class TrainingOut(BaseModel):
    """Act as me in training, per setting, and what it learned there."""

    replies: bool
    follow_ups: bool
    actions: bool
    drafts: bool
    # Suggested actions On: carried out with no allow (false while in training).
    actions_on: bool = False
    # The caller's own, newest first.
    learned: list[LearnedOut] = []


class TrainingUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid")

    replies: bool | None = None
    follow_ups: bool | None = None
    actions: bool | None = None
    drafts: bool | None = None
    actions_on: bool | None = None


class HandleItOut(BaseModel):
    """Handle it for me: the switch and its setting (careful, balanced, bold)."""

    enabled: bool
    mode: str
    # Whether this server can tie the switch to the person (signed sign-ins
    # or local login); without it nothing is sent on its own.
    available: bool
    sent_today: int = 0
    # Take the lead as you: the setting's limits give way to the added rules
    # (orchestrator.take_the_lead). Only the owner can have it in this build.
    lead: bool = False
    lead_available: bool = False


class LeadUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid")

    enabled: bool


class LeadRuleIn(BaseModel):
    model_config = ConfigDict(extra="forbid")

    kind: str
    value: str


class LeadRuleOut(BaseModel):
    id: int
    kind: str
    value: str


class LeadRulesOut(BaseModel):
    rules: list[LeadRuleOut]


class HandleItUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid")

    enabled: bool | None = None
    mode: str | None = None


class DisclosureOut(BaseModel):
    """The AI line on replies sent as the caller (delegation.disclosure):
    on those Handle it for me sends on its own, and on drafts they send.
    ``enabled`` is the install's AI_DISCLOSURE: off, neither is added."""

    enabled: bool
    handle_it: bool
    approved_sends: bool
    line: str


class CalendarOut(BaseModel):
    """Read my calendar (delegation.calendar): the caller's own switch,
    whether their mailbox sign-in includes the calendar (None when their
    mailbox isn't connected or the provider didn't say), and the command that
    connects it with calendar access."""

    enabled: bool
    granted: bool | None = None
    connect_command: str


class CalendarUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid")

    enabled: bool


class DisclosureUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid")

    handle_it: bool | None = None
    approved_sends: bool | None = None


class HandledReplyOut(BaseModel):
    decision_id: int
    sent_at: str
    to_name: str
    to_email: str
    subject: str
    body: str
    open_questions: list[str]
    gmail_link: str
    # "follow_up" for a follow-up to the caller's own unanswered email;
    # "invite" for a meeting invite it accepted on its own.
    source: str = ""
    # What it did, in one line, for an invite: "Accepted Dana's Pilot
    # review, Wed 21 Oct, 14:30".
    summary: str = ""


class HandledOut(BaseModel):
    replies: list[HandledReplyOut]


class DelegationOut(BaseModel):
    enabled: bool
    gmail: GmailConnection
    inbox: InboxOut
    # Absent on a backend that predates Handle it for me.
    handle_it: HandleItOut | None = None
    # Absent on a backend that predates per-setting training.
    training: TrainingOut | None = None
    # Absent on a backend that predates the AI line on replies.
    disclosure: DisclosureOut | None = None
    # Absent on a backend that predates Read my calendar.
    calendar: CalendarOut | None = None
    # The principal's "Let team members use Act as me", while the install
    # allows it; None for anyone else.
    team: TeamOut | None = None


class TeamUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid")

    enabled: bool


class InboxUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid")

    enabled: bool | None = None
    # Also save each reply in the caller's mailbox's Drafts.
    mailbox_drafts: bool | None = None


class ReplyQuestionOut(BaseModel):
    """One thing a reply card leaves the caller to decide."""

    text: str
    # 2 to 4 short answers to tap, or none.
    choices: list[str] = Field(default_factory=list)
    # Where the choices came from: their calendar or a document ("" for none).
    source: str = ""
    # The answer they gave from the card ("" while it is open).
    answer: str = ""


class ReplyTurnOut(BaseModel):
    """One turn of a reply card's conversation since its draft was written."""

    # "news": newer email in the conversation; "asked": what the caller asked
    # to change; "note": the Executive's line on what it changed.
    kind: str
    text: str
    from_name: str = ""
    from_email: str = ""
    at: str = ""


class ReplyCardOut(BaseModel):
    decision_id: int
    status: str
    created_at: str
    thread_id: str
    from_name: str
    from_email: str
    relation: str
    sender_verified: bool
    subject: str
    received_at: str
    they_wrote: str
    draft_to: list[str]
    draft_subject: str
    draft_body: str
    open_questions: list[str]
    flags: list[str]
    gmail_link: str
    # Why Handle it for me left it for you ("" when it didn't decide).
    waited_because: str = ""
    # "follow_up": the draft chases the caller's own unanswered email.
    source: str = ""
    # In training: Send + allow is offered (delegation.training).
    can_allow: bool = False
    # Drafts in training: "Do it like this next time" is offered.
    learns_style: bool = False
    # Also in the caller's mailbox's Drafts; False: on this card alone.
    in_mailbox: bool = True
    # Which of their mailboxes it sends from: "Gmail" or "Outlook".
    mailbox: str = "Gmail"
    # The open questions with what can be tapped to answer each; on a card
    # made before choices, each has none.
    questions: list[ReplyQuestionOut] = Field(default_factory=list)
    # Changed by hand on the card: what is left open no longer holds Send.
    questions_settled: bool = False
    # POST .../answer only: the sentences its rewrite added or changed.
    changed_sentences: list[str] = Field(default_factory=list)
    # Everyone else the email went to: Reply to: Everyone adds them. Empty
    # when there is no choice to make.
    reply_others: list[str] = Field(default_factory=list)
    # What the email asks and what the draft says, in a line or two, for the
    # card's closed view ("" on a card drafted before it).
    gist: str = ""
    # Newer email in the conversation, what the caller asked to change and
    # what the Executive changed, in order.
    conversation: list[ReplyTurnOut] = Field(default_factory=list)
    # When it was last brought up to date with newer mail; Send passes it
    # back as edits.seen_caught_up_at.
    caught_up_at: str = ""


class RepliesOut(BaseModel):
    cards: list[ReplyCardOut]


class ReplyTextUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid")

    text: str = Field(max_length=20_000)


class ChatDraftSendIn(BaseModel):
    model_config = ConfigDict(extra="forbid")

    # The second yes for a reply whose conversation moved on since.
    thread_moved_on: bool = False


class ChatDraftSentOut(BaseModel):
    sent: bool = True


class ReplyRecipientsUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid")

    # True: everyone the email went to; False: the sender only.
    everyone: bool


class ReplyAnswerIn(BaseModel):
    model_config = ConfigDict(extra="forbid")

    question_index: int = Field(ge=0, le=20)
    answer_text: str = Field(min_length=1, max_length=500)


class ReplyChangeIn(BaseModel):
    model_config = ConfigDict(extra="forbid")

    text: str = Field(min_length=1, max_length=500)


class ReplyAnswersIn(BaseModel):
    model_config = ConfigDict(extra="forbid")

    answers: list[ReplyAnswerIn] = Field(min_length=1, max_length=6)


class CardActionOut(BaseModel):
    index: int
    # invite, message or add_contact.
    kind: str
    summary: str
    # A message's text as it will be sent, or a meeting's description.
    text: str


class InviteCardOut(BaseModel):
    decision_id: int
    status: str
    created_at: str
    from_name: str
    from_email: str
    relation: str
    title: str
    # When, as the caller reads it: "Wed 21 Oct, 14:30–15:00".
    when: str
    start: str
    end: str
    all_day: bool
    # Busy times on their calendar that overlap it ("14:00–14:30"); times only.
    clashes: list[str]
    # False: their calendar couldn't be read for clashes.
    clash_checked: bool
    # False: their sign-in reads the calendar but can't answer invites, so the
    # card says to connect again (connect_command) instead of offering Accept.
    can_answer: bool
    # In training: the "Accept from them on its own next time" tick.
    can_allow: bool
    # Why Handle it for me left it for them, in words ("" when it was off).
    waited_because: str
    connect_command: str


class InviteCardsOut(BaseModel):
    cards: list[InviteCardOut]


class ActionCardOut(BaseModel):
    decision_id: int
    status: str
    created_at: str
    why: str
    actions: list[CardActionOut]
    # In training: Approve + allow is offered (delegation.training).
    can_allow: bool = False


class ActionCardsOut(BaseModel):
    cards: list[ActionCardOut]


class DelegationUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid")

    enabled: bool


class VoiceOut(BaseModel):
    greetings: dict[str, str]
    sign_off: str
    signature: str
    length: str
    formality: str
    habits: list[str]
    avoid: list[str]
    exemplars: list[str]
    locked: bool
    learned_at: str | None
    sample_count: int
    updated_at: str | None
    # "learn" when a learn pass made the last change, else "person:<id>".
    updated_by: str | None = None


class VoiceUpdate(BaseModel):
    """Fields to change; anything left out stays as it is."""

    model_config = ConfigDict(extra="forbid")

    greetings: dict[str, str] | None = None
    sign_off: str | None = None
    length: str | None = None
    formality: str | None = None
    habits: list[str] | None = None
    avoid: list[str] | None = None
    locked: bool | None = None
    clear_exemplars: bool = False
    clear_signature: bool = False


class VoiceDescribeIn(BaseModel):
    model_config = ConfigDict(extra="forbid")

    # A little over the limit, so a long paste gets the plain 409 message.
    description: str = Field(max_length=DESCRIPTION_MAX_CHARS * 2)


class VoiceDescribedOut(BaseModel):
    """A style written from the caller's words, not saved yet."""

    greetings: dict[str, str]
    sign_off: str
    length: str
    formality: str
    habits: list[str]
    avoid: list[str]
    sample_reply: str


# What a refused field must be, for the message an edit gets back.
_VOICE_RULES: dict[str, str] = {
    "greetings": "a greeting is one short line, and {first} is its only placeholder",
    "sign_off": "the sign-off is at most two short lines",
    "habits": "a habit or never-rule says how you write, without anyone's name",
    "avoid": "a habit or never-rule says how you write, without anyone's name",
}


def _refuse(status_code: int, code: str, message: str) -> HTTPException:
    return HTTPException(status_code=status_code, detail={"code": code, "message": message})


def _caller(request: Request) -> Person:
    """The signed-in caller, when they may have Act as me; else 403. Found
    through the app's one caller resolver (``chat._resolve_caller_person_id``),
    so a deployment that maps a signed-in account to its person there is
    followed here too. A request that names no one only counts as the
    principal under local login."""
    from openexecutive.api.routes.chat import _resolve_caller_person_id
    from openexecutive.people.store import find_principal_person, get_person

    who = api_caller.caller(request)
    if not who.email and not (who.defaults_to_principal and local_login()):
        raise _refuse(403, "sign_in_required", "Sign in to change Act as me.")
    try:
        person_id = _resolve_caller_person_id(request)
        if person_id is None:
            # The resolver reads a roster it can't open as "no one"; read it
            # once more so an outage answers 503, not "not for you".
            find_principal_person()
        person = get_person(person_id) if person_id is not None else None
    except Exception as exc:
        logger.exception("delegation: caller lookup failed")
        raise _refuse(503, "roster_unavailable", "Couldn't read the People list.") from exc
    if person is None or not can_delegate(person):
        raise _refuse(403, "not_available_yet", _NOT_AVAILABLE)
    return person


_NOT_AVAILABLE = "Act as me isn't available to you here. The account owner can let team members use it."


def _person_id(person: Person) -> int:
    if person.id is None:  # can_delegate already requires one
        raise _refuse(403, "not_available_yet", _NOT_AVAILABLE)
    return person.id


def _connect_command(email: str | None) -> str:
    target = email or "[email protected]"
    return (
        "uv run --with google-auth-oauthlib python scripts/connect-own-gmail.py "
        f"--email {target}"
    )


def _outlook_connect_command(email: str | None) -> str:
    target = email or "[email protected]"
    return f"uv run python scripts/connect-own-outlook.py --email {target}"


async def _calendar_out(person: Person, status: str) -> CalendarOut:
    from openexecutive.delegation import calendar

    email = person.email or ""
    outlook = bool(email) and credential_provider(email) == "microsoft"
    command = _outlook_connect_command(email) if outlook else _connect_command(email)
    granted: bool | None = None
    if status == "connected":
        # The status check just refreshed the sign-in, so this reads the
        # scopes it came back with rather than asking again.
        try:
            granted = await gmail_for(email).calendar_granted()
        except Exception:
            logger.warning("delegation: couldn't tell whether the sign-in includes the calendar", exc_info=True)
    return CalendarOut(enabled=calendar.enabled(person.id), granted=granted, connect_command=f"{command} --calendar")


def _inbox_out(person_id: int) -> InboxOut:
    from openexecutive.delegation import inbox

    watch = inbox.get_watch(person_id)
    checking = inbox.scanning(person_id)
    status = "checking" if checking else watch.status
    return InboxOut(
        enabled=watch.enabled,
        status=status,
        message=inbox.STATUS_MESSAGES.get(status, inbox.STATUS_MESSAGES["ok"]),
        watch_since=watch.watch_since,
        last_poll_at=watch.last_poll_at,
        checking=checking,
        mailbox_drafts=watch.mailbox_drafts,
    )


def _team_out(person: Person) -> TeamOut | None:
    """The owner's switch and each team member's counts, for the principal
    while the install allows it; None otherwise."""
    from datetime import UTC, datetime, timedelta

    from openexecutive.delegation import drafts, inbox
    from openexecutive.people.store import get_person

    if not person.is_principal or not team_members_available():
        return None
    since = datetime.now(UTC) - timedelta(days=30)
    members: list[TeamMemberUse] = []
    for person_id in enabled_person_ids():
        if person_id == person.id:
            continue
        try:
            member = get_person(person_id)
            if member is None or member.archived or member.kind != "team":
                continue
            drafted, sent = drafts.usage_since(person_id, since)
            watching = inbox.get_watch(person_id).enabled
        except Exception:
            logger.warning("delegation: couldn't read a team member's use", exc_info=True)
            continue
        members.append(TeamMemberUse(
            person_id=person_id, name=member.full_name or member.email or f"Person {person_id}",
            enabled=True, inbox=watching, drafts_30d=drafted, sent_30d=sent,
        ))
    return TeamOut(enabled=team_members_switch(), members=members)


async def _state(person: Person) -> DelegationOut:
    status = await gmail_status(person.email)
    return DelegationOut(
        enabled=is_enabled(person.id),
        gmail=GmailConnection(
            status=status,
            message=STATUS_MESSAGES[status],
            email=person.email,
            connect_command=_connect_command(person.email),
            outlook_connect_command=_outlook_connect_command(person.email),
            provider=credential_provider(person.email or ""),
        ),
        inbox=_inbox_out(_person_id(person)),
        handle_it=_handle_it_out(_person_id(person)),
        training=_training_out(_person_id(person)),
        disclosure=_disclosure_out(_person_id(person)),
        calendar=await _calendar_out(person, status),
        team=_team_out(person),
    )


def _disclosure_out(person_id: int) -> DisclosureOut:
    from openexecutive.delegation import disclosure
    from openexecutive.orchestrator.disclosure import enabled

    switches = disclosure.get(person_id)
    return DisclosureOut(
        enabled=enabled(), handle_it=switches.handle_it, approved_sends=switches.approved_sends,
        line=disclosure.LINE,
    )


def _handle_it_out(person_id: int) -> HandleItOut:
    from datetime import UTC, datetime

    from openexecutive.delegation import handle_it, training
    from openexecutive.people.store import get_person

    stored = handle_it.get(person_id)
    trained = training.get(person_id).replies
    try:
        today = handle_it.sent_today(person_id, datetime.now(UTC))
    except Exception:
        today = 0
    try:
        found = get_person(person_id)
        principal = bool(found is not None and found.is_principal)
    except Exception:
        principal = False
    return HandleItOut(
        enabled=stored.enabled, mode=stored.mode, available=handle_it.signing_ok(), sent_today=today,
        lead=principal and stored.enabled and not trained and handle_it.leading(person_id),
        lead_available=principal,
    )


def _training_out(person_id: int) -> TrainingOut:
    from openexecutive.delegation import training

    switches = training.get(person_id)
    try:
        learned = [
            LearnedOut(
                id=a.id, label=a.label, setting=training.setting_of(a.key), example=_example_text(a.example),
                uses=a.uses, created_at=a.created_at,
            )
            for a in training.learned(person_id)
        ]
    except Exception:
        logger.warning("delegation: couldn't read what Act as me learned", exc_info=True)
        learned = []
    return TrainingOut(
        replies=switches.replies, follow_ups=switches.follow_ups, actions=switches.actions,
        drafts=switches.drafts, actions_on=switches.actions_without_asking, learned=learned,
    )


def _example_text(stored: str) -> str:
    import json

    try:
        text = json.loads(stored).get("text") if stored else ""
    except (ValueError, AttributeError):
        return ""
    return text if isinstance(text, str) else ""


def _audit(event_type: str, summary: str, details: dict[str, Any]) -> None:
    from openexecutive.audit import log_event

    person_id = details.get("person_id")
    log_event(
        event_type, summary, actor="user", details=details, private=True,
        private_to_person=person_id if isinstance(person_id, int) else None,
    )


def _voice_out(stored: StoredVoice) -> VoiceOut:
    p = stored.profile
    return VoiceOut(
        greetings=dict(p.greetings),
        sign_off=p.sign_off,
        signature=p.signature,
        length=p.length,
        formality=p.formality,
        habits=list(p.habits),
        avoid=list(p.avoid),
        exemplars=list(p.exemplars),
        locked=stored.locked,
        learned_at=stored.learned_at,
        sample_count=stored.sample_count,
        updated_at=stored.updated_at,
        updated_by=stored.updated_by,
    )


@router.get("/delegation", response_model=DelegationOut)
async def get_delegation(request: Request) -> DelegationOut:
    return await _state(_caller(request))


@router.put("/delegation", response_model=DelegationOut)
async def update_delegation(request: Request, body: DelegationUpdate) -> DelegationOut:
    person = _caller(request)
    person_id = _person_id(person)
    if body.enabled:
        status = await gmail_status(person.email)
        if status != "connected":
            raise _refuse(409, _BLOCKING_CODES.get(status, "gmail_error"), STATUS_MESSAGES[status])
    before = is_enabled(person_id)
    if not body.enabled:
        # The inbox watcher needs Act as me; off here, it starts from scratch
        # (watch_since) when turned on again, never catching up.
        _set_inbox(person_id, False)
        _set_calendar(person_id, False)
        # Where their emails are (read_my_email's list): only kept while it's on.
        # Best-effort, so a failure here never keeps Act as me on.
        from openexecutive.delegation import mail_reads

        try:
            mail_reads.forget(person_id)
        except Exception:
            logger.warning("delegation: couldn't forget the emails it opened for person %s", person_id, exc_info=True)
    if before != body.enabled:
        set_enabled(person_id, body.enabled, updated_by=f"person:{person_id}")
        if body.enabled:
            _audit(
                "delegation_gmail_verified",
                f"Checked person {person_id}'s own Gmail before turning Act as me on",
                {"person_id": person_id, "status": "connected"},
            )
        _audit(
            "delegation_settings_changed",
            f"Act as me turned {'on' if body.enabled else 'off'} by person {person_id}",
            {"person_id": person_id, "enabled": body.enabled},
        )
    return await _state(person)


@router.put("/delegation/team", response_model=DelegationOut)
async def update_delegation_team(request: Request, body: TeamUpdate) -> DelegationOut:
    """The owner's "Let team members use Act as me". Off takes it away from
    every team member from their next message (``can_delegate``), and their
    inbox watchers stop at their next check; their own switches, drafts and
    cards are kept for if it is turned on again."""
    person = _caller(request)
    person_id = _person_id(person)
    if not person.is_principal:
        raise _refuse(403, "principal_only", "Only the account owner can change this.")
    if not team_members_available():
        raise _refuse(409, "not_available", "Act as me for team members isn't available on this install.")
    if team_members_switch() != body.enabled:
        set_team_members(body.enabled, updated_by=f"person:{person_id}")
        _audit(
            "delegation_settings_changed",
            f"Act as me for team members turned {'on' if body.enabled else 'off'} by person {person_id}",
            {"person_id": person_id, "team_members": body.enabled},
        )
    return await _state(person)


def _set_inbox(person_id: int, enabled: bool) -> None:
    from openexecutive.delegation import inbox

    if not enabled:
        # Handle it for me sends what the watcher drafts: it goes with it.
        _set_handle_it(person_id, enabled=False, mode=None)
    before = inbox.get_watch(person_id).enabled
    if before == enabled:
        return
    inbox.set_watch(person_id, enabled, updated_by=f"person:{person_id}")
    _audit(
        "delegation_inbox_changed",
        f"Draft replies to my inbox turned {'on' if enabled else 'off'} by person {person_id}",
        {"person_id": person_id, "enabled": enabled},
    )


# Checks started from the card, kept so they aren't collected mid-run.
_CHECKS: set[asyncio.Task[Any]] = set()


@router.put("/delegation/inbox", response_model=DelegationOut)
async def update_delegation_inbox(request: Request, body: InboxUpdate) -> DelegationOut:
    person = _caller(request)
    person_id = _person_id(person)
    if body.enabled is None and body.mailbox_drafts is None:
        raise _refuse(422, "nothing_to_change", "Say what to change.")
    if body.enabled:
        if not is_enabled(person_id):
            raise _refuse(409, "act_as_me_off", "Turn Act as me on first.")
        status = await gmail_status(person.email)
        if status != "connected":
            raise _refuse(409, _BLOCKING_CODES.get(status, "gmail_error"), STATUS_MESSAGES[status])
    if body.mailbox_drafts is not None:
        _set_mailbox_drafts(person_id, body.mailbox_drafts)
    if body.enabled is not None:
        _set_inbox(person_id, body.enabled)
    return await _state(person)


def _set_mailbox_drafts(person_id: int, on: bool) -> None:
    """Whether replies are also saved in the caller's mailbox's Drafts. Cards
    already made keep where their reply is."""
    from openexecutive.delegation import inbox

    if inbox.get_watch(person_id).mailbox_drafts == on:
        return
    inbox.set_mailbox_drafts(person_id, on, updated_by=f"person:{person_id}")
    _audit(
        "delegation_inbox_changed",
        f"Also save replies in my Drafts turned {'on' if on else 'off'} by person {person_id}",
        {"person_id": person_id, "mailbox_drafts": on},
    )


@router.post("/delegation/inbox/check", status_code=202, response_model=InboxOut)
async def check_delegation_inbox(request: Request) -> InboxOut:
    """Check the caller's inbox now, in the background; ``GET /delegation``
    shows when it is done."""
    from openexecutive.audit.context import unscoped_audit_rows
    from openexecutive.delegation import inbox

    person = _caller(request)
    person_id = _person_id(person)
    if not inbox.get_watch(person_id).enabled:
        raise _refuse(409, "inbox_off", "Turn on Draft replies to my inbox first.")
    if inbox.scanning(person_id):
        raise _refuse(409, "in_progress", "It's checking your inbox already.")
    with unscoped_audit_rows():
        task = asyncio.create_task(inbox.scan_person(person))
    _CHECKS.add(task)
    task.add_done_callback(_CHECKS.discard)
    # The scan marks itself as running on its first step; say so either way.
    out = _inbox_out(person_id)
    return out.model_copy(update={"checking": True, "status": "checking",
                                  "message": inbox.STATUS_MESSAGES["checking"]})


@router.get("/delegation/replies", response_model=RepliesOut)
def get_delegation_replies(request: Request) -> RepliesOut:
    """The reply cards waiting for the caller. Their own only: everyone else
    gets the 403 every route here gives."""
    from openexecutive.delegation.replies import cards

    person = _caller(request)
    _person_id(person)
    try:
        found = cards(person)
    except Exception as exc:
        logger.exception("delegation: reading the reply cards failed")
        raise _refuse(503, "unavailable", "Couldn't read the replies waiting for you.") from exc
    return RepliesOut(cards=[
        ReplyCardOut(**{k: v for k, v in asdict(card).items() if k in ReplyCardOut.model_fields})
        for card in found
    ])


class MailAttachmentOut(BaseModel):
    name: str
    mime_type: str = ""
    size: int = 0


class MailViewOut(BaseModel):
    """One email in the caller's own mailbox, as Home opens it from a Right
    now point: who wrote, to whom, what they wrote (without the quoted
    conversation below), its files, what the caller last wrote in the
    conversation, a link to it in their mailbox, and the reply card open on
    the conversation, if any."""

    thread_id: str
    message_id: str
    subject: str = ""
    from_name: str = ""
    from_email: str = ""
    to: list[str] = Field(default_factory=list)
    cc: list[str] = Field(default_factory=list)
    received_at: str = ""
    text: str = ""
    attachments: list[MailAttachmentOut] = Field(default_factory=list)
    has_attachments: bool = False
    their_last_words: str = ""
    link: str = ""
    reply_card_id: int | None = None


class MailReplyIn(BaseModel):
    model_config = ConfigDict(extra="forbid")

    thread_id: str = Field(min_length=1, max_length=512)
    message_id: str = Field(min_length=1, max_length=512)


class MailReplyOut(BaseModel):
    decision_id: int


# The most of an email's own words Home shows.
_MAIL_VIEW_MAX_CHARS = 8000
_MAIL_EARLIER_MAX_CHARS = 400


async def _connected_mailbox(person: Person) -> Any:
    status = await gmail_status(person.email)
    if status != "connected":
        raise _refuse(409, _BLOCKING_CODES.get(status, "gmail_error"), STATUS_MESSAGES[status])
    return gmail_for(person.email or "")


@router.get("/delegation/mail", response_model=MailViewOut)
async def get_delegation_mail(request: Request, thread_id: str, message_id: str) -> MailViewOut:
    """One email in the caller's own mailbox (Home's View email). Their own
    mailbox only: the client is theirs, so another person's ids find
    nothing. Reads; changes nothing."""
    from openexecutive.delegation.gmail import GmailNotFound, mailbox_link
    from openexecutive.delegation.inbox import card_payload, open_cards
    from openexecutive.delegation.inbox_classifier import their_last_words
    from openexecutive.integrations.email_poller import sender_new_text

    person = _caller(request)
    person_id = _person_id(person)
    if not (0 < len(thread_id) <= 512 and 0 < len(message_id) <= 512):
        raise _refuse(422, "bad_id", "That isn't an email.")
    client = await _connected_mailbox(person)
    try:
        thread = await client.get_thread(thread_id)
        own = {(person.email or "").strip().lower(), *(a.strip().lower() for a in await client.send_as_addresses())}
    except GmailNotFound as exc:
        raise _refuse(404, "not_found", "That email isn't in your mailbox any more.") from exc
    except GmailAuthError as exc:
        raise _refuse(409, "gmail_needs_reconnect", STATUS_MESSAGES["needs_reconnect"]) from exc
    except GmailError as exc:
        logger.warning("delegation: reading an email failed", exc_info=True)
        raise _refuse(502, "gmail_error", STATUS_MESSAGES["error"]) from exc
    message = next((m for m in thread.messages if m.id == message_id), None)
    if message is None:
        raise _refuse(404, "not_found", "That email isn't in your mailbox any more.")
    card = next(
        (c for c in open_cards(person_id) if card_payload(c).get("thread_id") == thread.id), None
    )
    return MailViewOut(
        thread_id=thread.id,
        message_id=message.id,
        subject=message.subject,
        from_name=message.from_name,
        from_email=message.from_addr,
        to=list(message.to),
        cc=list(message.cc),
        received_at=message.received_at,
        text=sender_new_text(message.text or "")[:_MAIL_VIEW_MAX_CHARS].strip(),
        attachments=[
            MailAttachmentOut(name=a.name, mime_type=a.mime_type, size=a.size) for a in message.attachments
        ],
        has_attachments=bool(message.attachments) or message.has_attachments,
        their_last_words=their_last_words(thread, message, own)[:_MAIL_EARLIER_MAX_CHARS],
        link=mailbox_link(person.email or "", thread_id=thread.id, message_id=message.id),
        reply_card_id=int(card.id) if card is not None else None,
    )


@router.post("/delegation/mail/reply", response_model=MailReplyOut)
async def reply_to_delegation_mail(request: Request, body: MailReplyIn) -> MailReplyOut:
    """Write a reply to one email in the caller's own inbox, because they
    asked (Home's Reply), and put it on a reply card for them
    (``delegation.inbox.draft_on_request``). The open card already on that
    conversation when there is one. Sends nothing: the card's Send does."""
    from openexecutive.delegation.inbox import ASK_REFUSALS, draft_on_request

    person = _caller(request)
    person_id = _person_id(person)
    if not is_enabled(person_id):
        raise _refuse(409, "act_as_me_off", "Turn Act as me on first.")
    client = await _connected_mailbox(person)
    try:
        got = await draft_on_request(person, body.thread_id, body.message_id, gmail=client)
    except GmailAuthError as exc:
        raise _refuse(409, "gmail_needs_reconnect", STATUS_MESSAGES["needs_reconnect"]) from exc
    except GmailError as exc:
        logger.warning("delegation: writing a reply on request failed", exc_info=True)
        raise _refuse(502, "gmail_error", STATUS_MESSAGES["error"]) from exc
    if isinstance(got, str):
        raise _refuse(409, got, ASK_REFUSALS.get(got, ASK_REFUSALS["not_now"]))
    return MailReplyOut(decision_id=got)


@router.put("/delegation/replies/{decision_id}/text", response_model=ReplyCardOut)
async def update_delegation_reply_text(request: Request, decision_id: int, body: ReplyTextUpdate) -> ReplyCardOut:
    """Change the words of one of the caller's reply cards before Send: on
    the card, and in their mailbox's Drafts when it is there too
    (``delegation.card_drafts.edit``). Their own cards only; sends nothing."""
    from openexecutive.delegation import card_drafts
    from openexecutive.delegation.inbox import DECISION_CLASS
    from openexecutive.delegation.replies import cards
    from openexecutive.delegation.reply_send import SendRefused
    from openexecutive.memory.decision_ledger import get_decision_instance

    person = _caller(request)
    person_id = _person_id(person)
    instance = get_decision_instance(decision_id)
    if instance is None or instance.decision_class != DECISION_CLASS or instance.approver_person_id != person_id:
        raise _refuse(404, "not_found", "That reply isn't waiting for you any more.")
    try:
        await card_drafts.edit(instance, caller=api_caller.caller(request), resolver=person_id, text=body.text)
    except SendRefused as refused:
        raise HTTPException(
            status_code=refused.status, detail={"code": refused.code, "message": refused.message, **refused.extra},
        ) from None
    card = next((c for c in cards(person) if c.decision_id == decision_id), None)
    if card is None:
        raise _refuse(404, "not_found", "That reply isn't waiting for you any more.")
    return ReplyCardOut(**{k: v for k, v in asdict(card).items() if k in ReplyCardOut.model_fields})


@router.post("/delegation/drafts/{row_id}/send", response_model=ChatDraftSentOut)
async def send_chat_draft(request: Request, row_id: int, body: ChatDraftSendIn) -> ChatDraftSentOut:
    """Send a draft chat wrote as the caller, on their tap, exactly as it was
    written (``delegation.reply_send.send_chat_draft``, which checks
    everything again first). Their own drafts only."""
    from openexecutive.delegation.reply_send import SendRefused
    from openexecutive.delegation.reply_send import send_chat_draft as send

    person = _caller(request)
    try:
        await send(
            person, row_id, caller=api_caller.caller(request),
            confirm={"thread_moved_on": True} if body.thread_moved_on else None,
        )
    except SendRefused as refused:
        raise HTTPException(
            status_code=refused.status, detail={"code": refused.code, "message": refused.message, **refused.extra},
        ) from None
    return ChatDraftSentOut()


@router.put("/delegation/replies/{decision_id}/recipients", response_model=ReplyCardOut)
async def update_delegation_reply_recipients(
    request: Request, decision_id: int, body: ReplyRecipientsUpdate,
) -> ReplyCardOut:
    """Send one of the caller's replies to the sender only, or to everyone the
    email went to: on the card, and in their mailbox's Drafts when it is there
    too (``delegation.card_drafts.set_recipients``). Only the lists the card
    was written with; no address comes from the request. Their own cards
    only; sends nothing."""
    from openexecutive.delegation import card_drafts
    from openexecutive.delegation.inbox import DECISION_CLASS
    from openexecutive.delegation.replies import cards
    from openexecutive.delegation.reply_send import SendRefused
    from openexecutive.memory.decision_ledger import get_decision_instance

    person = _caller(request)
    person_id = _person_id(person)
    instance = get_decision_instance(decision_id)
    if instance is None or instance.decision_class != DECISION_CLASS or instance.approver_person_id != person_id:
        raise _refuse(404, "not_found", "That reply isn't waiting for you any more.")
    try:
        await card_drafts.set_recipients(
            instance, caller=api_caller.caller(request), resolver=person_id, everyone=body.everyone,
        )
    except SendRefused as refused:
        raise HTTPException(
            status_code=refused.status, detail={"code": refused.code, "message": refused.message, **refused.extra},
        ) from None
    card = next((c for c in cards(person) if c.decision_id == decision_id), None)
    if card is None:
        raise _refuse(404, "not_found", "That reply isn't waiting for you any more.")
    return ReplyCardOut(**{k: v for k, v in asdict(card).items() if k in ReplyCardOut.model_fields})


@router.post("/delegation/replies/{decision_id}/answer", response_model=ReplyCardOut)
async def answer_delegation_reply(request: Request, decision_id: int, body: ReplyAnswersIn) -> ReplyCardOut:
    """Answer what one of the caller's reply cards left them to decide:
    the draft is rewritten with the answers in their voice and saved like a
    change of its words (``delegation.answers.answer`` through
    ``card_drafts.edit``: the same caller and card checks, and the same
    update in their Drafts when it is there). Their own cards only; sends
    nothing. 429 past ``answers.ANSWERS_PER_HOUR`` rewrites an hour."""
    from openexecutive.delegation import answers
    from openexecutive.delegation.inbox import DECISION_CLASS
    from openexecutive.delegation.replies import cards
    from openexecutive.delegation.reply_send import SendRefused
    from openexecutive.memory.decision_ledger import get_decision_instance

    person = _caller(request)
    person_id = _person_id(person)
    instance = get_decision_instance(decision_id)
    if instance is None or instance.decision_class != DECISION_CLASS or instance.approver_person_id != person_id:
        raise _refuse(404, "not_found", "That reply isn't waiting for you any more.")
    try:
        _, changed = await answers.answer(
            instance,
            caller=api_caller.caller(request),
            resolver=person_id,
            answers=[answers.Answer(question_index=a.question_index, text=a.answer_text) for a in body.answers],
        )
    except SendRefused as refused:
        raise HTTPException(
            status_code=refused.status, detail={"code": refused.code, "message": refused.message, **refused.extra},
        ) from None
    card = next((c for c in cards(person) if c.decision_id == decision_id), None)
    if card is None:
        raise _refuse(404, "not_found", "That reply isn't waiting for you any more.")
    out = ReplyCardOut(**{k: v for k, v in asdict(card).items() if k in ReplyCardOut.model_fields})
    return out.model_copy(update={"changed_sentences": changed})


@router.post("/delegation/replies/{decision_id}/change", response_model=ReplyCardOut)
async def change_delegation_reply(request: Request, decision_id: int, body: ReplyChangeIn) -> ReplyCardOut:
    """Change one of the caller's reply cards the way they said, in their
    own words: the draft is rewritten in their voice and saved like an
    answer (``delegation.answers.change`` through ``card_drafts.edit``: the
    same checks, the same update in their Drafts, the same hourly limit).
    Their own cards only; sends nothing."""
    from openexecutive.delegation import answers
    from openexecutive.delegation.inbox import DECISION_CLASS
    from openexecutive.delegation.replies import cards
    from openexecutive.delegation.reply_send import SendRefused
    from openexecutive.memory.decision_ledger import get_decision_instance

    person = _caller(request)
    person_id = _person_id(person)
    instance = get_decision_instance(decision_id)
    if instance is None or instance.decision_class != DECISION_CLASS or instance.approver_person_id != person_id:
        raise _refuse(404, "not_found", "That reply isn't waiting for you any more.")
    try:
        _, changed = await answers.change(
            instance, caller=api_caller.caller(request), resolver=person_id, text=body.text,
        )
    except SendRefused as refused:
        raise HTTPException(
            status_code=refused.status, detail={"code": refused.code, "message": refused.message, **refused.extra},
        ) from None
    card = next((c for c in cards(person) if c.decision_id == decision_id), None)
    if card is None:
        raise _refuse(404, "not_found", "That reply isn't waiting for you any more.")
    out = ReplyCardOut(**{k: v for k, v in asdict(card).items() if k in ReplyCardOut.model_fields})
    return out.model_copy(update={"changed_sentences": changed})


@router.get("/delegation/actions", response_model=ActionCardsOut)
def get_delegation_actions(request: Request) -> ActionCardsOut:
    """The action cards waiting for the caller to approve. Their own only:
    everyone else gets the 403 every route here gives."""
    from openexecutive.delegation.action_cards import cards

    person = _caller(request)
    _person_id(person)
    try:
        found = cards(person)
    except Exception as exc:
        logger.exception("delegation: reading the action cards failed")
        raise _refuse(503, "unavailable", "Couldn't read the cards waiting for you.") from exc
    return ActionCardsOut(cards=[
        ActionCardOut(
            decision_id=card.decision_id, status=card.status, created_at=card.created_at, why=card.why,
            actions=[CardActionOut(**asdict(a)) for a in card.actions], can_allow=card.can_allow,
        )
        for card in found
    ])


@router.get("/delegation/invites", response_model=InviteCardsOut)
def get_delegation_invites(request: Request) -> InviteCardsOut:
    """The meeting invite cards waiting for the caller to accept or decline.
    Their own only: everyone else gets the 403 every route here gives."""
    from openexecutive.delegation.invites import cards

    person = _caller(request)
    _person_id(person)
    try:
        found = cards(person)
    except Exception as exc:
        logger.exception("delegation: reading the invite cards failed")
        raise _refuse(503, "unavailable", "Couldn't read the invites waiting for you.") from exc
    return InviteCardsOut(cards=[InviteCardOut(**asdict(card)) for card in found])


def _set_handle_it(person_id: int, *, enabled: bool | None, mode: str | None) -> None:
    from openexecutive.delegation import handle_it

    if enabled is False:
        # Take the lead as you rides on Handle it; turning it back on later
        # starts from the dial, not from the lead.
        _lead_off(person_id)
    before = handle_it.get(person_id)
    if (enabled is None or enabled == before.enabled) and (mode is None or mode == before.mode):
        return
    after = handle_it.set_(person_id, enabled=enabled, mode=mode, updated_by=f"person:{person_id}")
    if after.enabled == before.enabled and after.mode == before.mode:
        return
    _audit(
        "delegation_handle_it_changed",
        f"Handle it for me {'on' if after.enabled else 'off'} for person {person_id}",
        {"person_id": person_id, "enabled": after.enabled, "mode": after.mode},
    )


def _lead_off(person_id: int) -> None:
    from openexecutive.orchestrator import take_the_lead

    scope = take_the_lead.person_scope(person_id)
    if take_the_lead.get(scope).enabled:
        take_the_lead.set_(scope, enabled=False, updated_by=f"person:{person_id}")


@router.put("/delegation/handle-it", response_model=DelegationOut)
async def update_delegation_handle_it(request: Request, body: HandleItUpdate) -> DelegationOut:
    from openexecutive.delegation import handle_it, inbox
    from openexecutive.delegation.gmail import normalize_email
    from openexecutive.delegation.verified import NOT_YOURS, caller_refusal

    person = _caller(request)
    person_id = _person_id(person)
    refused = caller_refusal(api_caller.caller(request), normalize_email(person.email or ""))
    if refused == NOT_YOURS:
        raise _refuse(403, "not_yours", "Only you can change Handle it for me.")
    # Turning it off only narrows what the watcher does, so it stays
    # possible after the server loses signed sign-ins.
    turning_off = body.enabled is False and body.mode is None
    if refused is not None and not turning_off:
        raise _refuse(
            409, "caller_signing_required",
            "Handle it for me needs signed sign-ins on this server, so that nobody else can turn it on for you.",
        )
    if body.mode is not None and body.mode not in handle_it.MODES:
        raise _refuse(422, "bad_mode", f"Unknown setting: {body.mode}.")
    if body.enabled:
        if not is_enabled(person_id):
            raise _refuse(409, "act_as_me_off", "Turn Act as me on first.")
        if not inbox.get_watch(person_id).enabled:
            raise _refuse(409, "inbox_off", "Turn on Draft replies to my inbox first.")
    _set_handle_it(person_id, enabled=body.enabled, mode=body.mode)
    return await _state(person)


def _set_calendar(person_id: int, enabled: bool) -> None:
    from openexecutive.delegation import calendar

    if calendar.enabled(person_id) == enabled:
        return
    calendar.set_enabled(person_id, enabled, updated_by=f"person:{person_id}")
    _audit(
        "delegation_calendar_changed",
        f"Read my calendar turned {'on' if enabled else 'off'} by person {person_id}",
        {"person_id": person_id, "enabled": enabled},
    )


@router.put("/delegation/calendar", response_model=DelegationOut)
async def update_delegation_calendar(request: Request, body: CalendarUpdate) -> DelegationOut:
    """Read my calendar, for the caller alone. On needs Act as me on and a
    calendar read that works (their sign-in must include the calendar); off
    always works."""
    from datetime import UTC, datetime, timedelta

    from openexecutive.delegation import calendar
    from openexecutive.delegation.gmail import CalendarNotGranted

    person = _caller(request)
    person_id = _person_id(person)
    if body.enabled:
        if not is_enabled(person_id):
            raise _refuse(409, "act_as_me_off", "Turn Act as me on first.")
        status = await gmail_status(person.email)
        if status != "connected":
            raise _refuse(409, _BLOCKING_CODES.get(status, "gmail_error"), STATUS_MESSAGES[status])
        now = datetime.now(UTC)
        try:
            await gmail_for(person.email or "").list_events(now, now + timedelta(hours=1), max_results=1)
        except CalendarNotGranted as exc:
            raise _refuse(409, "calendar_not_granted", calendar.NOT_GRANTED) from exc
        except GmailAuthError as exc:
            raise _refuse(409, "gmail_needs_reconnect", STATUS_MESSAGES["needs_reconnect"]) from exc
        except GmailError as exc:
            logger.warning("delegation: calendar check failed for person %s", person_id, exc_info=True)
            raise _refuse(503, "calendar_error", "Couldn't reach your calendar just now. Try again in a moment.") from exc
    _set_calendar(person_id, body.enabled)
    return await _state(person)


@router.put("/delegation/disclosure", response_model=DelegationOut)
async def update_delegation_disclosure(request: Request, body: DisclosureUpdate) -> DelegationOut:
    """The caller's own switches for the AI line on replies sent as them.
    Turning one on only adds the line, so it needs no signed sign-in;
    turning one off does, so nobody else can take it off their mail."""
    from openexecutive.delegation import disclosure

    changes = {k: v for k, v in body.model_dump().items() if v is not None}
    person = _signed_caller(request, narrowing=all(changes.values()))
    person_id = _person_id(person)
    before = disclosure.get(person_id)
    changed = {k: v for k, v in changes.items() if getattr(before, k) != v}
    if changed:
        disclosure.set_(person_id, **changed, updated_by=f"person:{person_id}")
        _audit(
            "delegation_disclosure_changed", f"AI line on replies changed for person {person_id}",
            {"person_id": person_id, **changed},
        )
    return await _state(person)


@router.put("/delegation/training", response_model=DelegationOut)
async def update_delegation_training(request: Request, body: TrainingUpdate) -> DelegationOut:
    """Put Act as me's settings in or out of training, or Suggested actions
    On (``actions_on``: carried out with no allow). Putting Replies or
    Follow-ups in only holds more back, and taking Suggested actions out of
    training or On stops cards being carried out on their own, so those need
    no signed sign-in; anything else does. Putting Replies or Follow-ups in turns Take
    the lead as you off: in training only what the person allowed goes."""
    from openexecutive.delegation import training

    changes = {k: v for k, v in body.model_dump().items() if v is not None}
    # Suggested actions is one of Always ask, In training or On: picking one
    # leaves the other.
    if changes.get(training.ACTIONS_ON) is True:
        changes[training.ACTIONS] = False
    elif training.ACTIONS in changes:
        # Out of training without asking for On is Always ask, never On.
        changes[training.ACTIONS_ON] = False
    narrowing = all(
        (v is True and k in (training.REPLIES, training.FOLLOW_UPS))
        or (v is False and k in (training.ACTIONS, training.ACTIONS_ON))
        for k, v in changes.items()
    )
    person = _signed_caller(request, narrowing=narrowing)
    person_id = _person_id(person)
    before = training.get(person_id)
    changed = {k: v for k, v in changes.items() if before.on(k) != v}
    if changed:
        if changed.get(training.REPLIES) or changed.get(training.FOLLOW_UPS):
            _lead_off(person_id)
        training.set_(person_id, changed, updated_by=f"person:{person_id}")
        _audit(
            "delegation_training_changed", f"Act as me training changed for person {person_id}",
            {"person_id": person_id, **changed},
        )
    return await _state(person)


@router.delete("/delegation/learned/{allowed_id}", response_model=DelegationOut)
async def delete_delegation_learned(request: Request, allowed_id: int) -> DelegationOut:
    """Forget one thing Act as me learned in training. Only the caller's
    own; holding more back, so no signed sign-in needed."""
    from openexecutive.delegation import training

    person = _signed_caller(request, narrowing=True)
    person_id = _person_id(person)
    if not training.forget(person_id, allowed_id):
        raise _refuse(404, "not_found", "That isn't there.")
    _audit(
        "delegation_learned_removed", f"Person {person_id} removed something Act as me had learned",
        {"person_id": person_id, "allowed_id": allowed_id},
    )
    return await _state(person)


def _signed_caller(request: Request, *, narrowing: bool) -> Person:
    """The caller, when this request is provably theirs; turning something
    off (``narrowing``) stays possible without signed sign-ins."""
    from openexecutive.delegation.gmail import normalize_email
    from openexecutive.delegation.verified import NOT_YOURS, caller_refusal

    person = _caller(request)
    refused = caller_refusal(api_caller.caller(request), normalize_email(person.email or ""))
    if refused == NOT_YOURS:
        raise _refuse(403, "not_yours", "Only you can change this.")
    if refused is not None and not narrowing:
        raise _refuse(
            409, "caller_signing_required",
            "This needs signed sign-ins on this server, so that nobody else can turn it on for you.",
        )
    return person


@router.put("/delegation/take-the-lead", response_model=DelegationOut)
async def update_take_the_lead_as_you(request: Request, body: LeadUpdate) -> DelegationOut:
    """Take the lead as you: the owner's own switch. Turning it on turns on
    Handle it for me too; turning it off leaves Handle it as it was."""
    from openexecutive.delegation import inbox, training
    from openexecutive.orchestrator import take_the_lead

    person = _signed_caller(request, narrowing=not body.enabled)
    person_id = _person_id(person)
    if not person.is_principal:
        raise _refuse(403, "owner_only", "Only the account owner can use Take the lead for now.")
    if body.enabled:
        if not is_enabled(person_id):
            raise _refuse(409, "act_as_me_off", "Turn Act as me on first.")
        if not inbox.get_watch(person_id).enabled:
            raise _refuse(409, "inbox_off", "Turn on Draft replies to my inbox first.")
        switches = training.get(person_id)
        if switches.replies or switches.follow_ups:
            raise _refuse(
                409, "in_training", "Replies or Follow-ups are in training. Take them out of training first.",
            )
        _set_handle_it(person_id, enabled=True, mode=None)
    scope = take_the_lead.person_scope(person_id)
    before = take_the_lead.get(scope).enabled
    take_the_lead.set_(scope, enabled=body.enabled, updated_by=f"person:{person_id}")
    if before != body.enabled:
        _audit(
            "take_the_lead_changed",
            f"Take the lead as you {'on' if body.enabled else 'off'} for person {person_id}",
            {"person_id": person_id, "scope": "as_you", "enabled": body.enabled},
        )
    return await _state(person)


# How far it goes as you: one dial over Write drafts as me, Draft replies to
# my inbox, Handle it for me and its level, and Everything (Take the lead as
# you). Each step adds to the one before it.
REACH_STEPS: tuple[str, ...] = ("off", "when_asked", "inbox", "careful", "balanced", "bold", "everything")
_SENDING_FROM = REACH_STEPS.index("careful")


class ReachUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid")

    step: Literal["off", "when_asked", "inbox", "careful", "balanced", "bold", "everything"]


def reach_of(person_id: int) -> str:
    """Where ``person_id`` is on the dial, from the switches it sets."""
    from openexecutive.delegation import handle_it, inbox, training

    if not is_enabled(person_id):
        return "off"
    if not inbox.get_watch(person_id).enabled:
        return "when_asked"
    stored = handle_it.get(person_id)
    if not stored.enabled:
        return "inbox"
    if not training.get(person_id).replies and handle_it.leading(person_id):
        return "everything"
    return stored.mode


@router.put("/delegation/reach", response_model=DelegationOut)
async def update_delegation_reach(request: Request, body: ReachUpdate) -> DelegationOut:
    """Move the dial. Going down turns the higher switches off first, top
    down, and needs no signed sign-in. Going up turns each one on in order
    through its own route, so every check that switch makes still applies
    (the mailbox connected, signed sign-ins, the owner alone for Everything,
    not in training); the first one that refuses stops the move there, at a
    step that is itself whole. Training is left as it is."""
    from openexecutive.delegation import handle_it

    person = _caller(request)
    person_id = _person_id(person)
    target = REACH_STEPS.index(body.step)
    current = REACH_STEPS.index(reach_of(person_id))
    if target == current:
        return await _state(person)

    # Down: highest first, so nothing is ever on above a switch that's off.
    if target < REACH_STEPS.index("everything"):
        _lead_off(person_id)
    if target < _SENDING_FROM:
        _set_handle_it(person_id, enabled=False, mode=None)
    if target < REACH_STEPS.index("inbox"):
        _set_inbox(person_id, False)
    if target < REACH_STEPS.index("when_asked"):
        return await update_delegation(request, DelegationUpdate(enabled=False))

    # Up, or across the sending steps: each switch through its own route.
    if not is_enabled(person_id):
        await update_delegation(request, DelegationUpdate(enabled=True))
    if target >= REACH_STEPS.index("inbox"):
        from openexecutive.delegation import inbox

        if not inbox.get_watch(person_id).enabled:
            await update_delegation_inbox(request, InboxUpdate(enabled=True))
    if target >= _SENDING_FROM:
        mode = body.step if body.step in handle_it.MODES else None
        stored = handle_it.get(person_id)
        if stored.enabled and mode is not None and handle_it.MODES.index(mode) < handle_it.MODES.index(stored.mode):
            # A lower level only holds more back: no signed sign-in needed.
            _set_handle_it(person_id, enabled=None, mode=mode)
        elif not stored.enabled or (mode is not None and mode != stored.mode):
            await update_delegation_handle_it(request, HandleItUpdate(enabled=True, mode=mode))
    if body.step == "everything":
        await update_take_the_lead_as_you(request, LeadUpdate(enabled=True))
    return await _state(person)

def _rules_out(person_id: int) -> LeadRulesOut:
    from openexecutive.orchestrator import take_the_lead

    try:
        rules = take_the_lead.list_rules([take_the_lead.person_scope(person_id)])
    except Exception as exc:
        raise _refuse(503, "unavailable", "Couldn't read your rules.") from exc
    return LeadRulesOut(rules=[LeadRuleOut(id=r.id, kind=r.kind, value=r.value) for r in rules])


@router.get("/delegation/take-the-lead/rules", response_model=LeadRulesOut)
def get_my_lead_rules(request: Request) -> LeadRulesOut:
    """The caller's own rules for Take the lead as you."""
    return _rules_out(_person_id(_caller(request)))


@router.post("/delegation/take-the-lead/rules", response_model=LeadRulesOut)
def add_my_lead_rule(request: Request, body: LeadRuleIn) -> LeadRulesOut:
    from openexecutive.orchestrator import take_the_lead

    # Adding a rule only holds more back, but it is still theirs alone.
    person = _signed_caller(request, narrowing=True)
    person_id = _person_id(person)
    try:
        take_the_lead.add_rule(
            take_the_lead.person_scope(person_id), body.kind, body.value, created_by=f"person:{person_id}",
        )
    except take_the_lead.RuleError as exc:
        raise _refuse(422, "bad_rule", str(exc)) from None
    return _rules_out(person_id)


@router.delete("/delegation/take-the-lead/rules/{rule_id}", response_model=LeadRulesOut)
def delete_my_lead_rule(request: Request, rule_id: int) -> LeadRulesOut:
    from openexecutive.orchestrator import take_the_lead

    # Removing a rule lets more go, so it needs the request to be provably theirs.
    person = _signed_caller(request, narrowing=False)
    person_id = _person_id(person)
    if not take_the_lead.delete_rule(rule_id, take_the_lead.person_scope(person_id)):
        raise _refuse(404, "not_found", "That rule isn't there.")
    return _rules_out(person_id)


@router.get("/delegation/handled", response_model=HandledOut)
def get_delegation_handled(request: Request) -> HandledOut:
    """What Handle it for me sent for the caller in the last 7 days. Their
    own only: everyone else gets the 403 every route here gives."""
    from openexecutive.delegation import handle_it
    from openexecutive.delegation.gmail import mailbox_link

    person = _caller(request)
    person_id = _person_id(person)
    email = (person.email or "").strip().lower()
    try:
        found = handle_it.handled(person_id)
    except Exception as exc:
        logger.exception("delegation: reading what was sent on its own failed")
        raise _refuse(503, "unavailable", "Couldn't read what it handled for you.") from exc
    return HandledOut(replies=[
        HandledReplyOut(
            decision_id=h.decision_id, sent_at=h.sent_at, to_name=h.to_name, to_email=h.to_email,
            subject=h.subject, body=h.body, open_questions=h.open_questions,
            gmail_link=mailbox_link(email, thread_id=h.thread_id) if email and h.thread_id else "",
            source=h.source,
            summary=h.summary,
        )
        for h in found
    ])


@router.get("/delegation/voice", response_model=VoiceOut)
def get_delegation_voice(request: Request) -> VoiceOut:
    person = _caller(request)
    return _voice_out(get_voice(_person_id(person)))


@router.post("/delegation/voice/learn", response_model=VoiceOut)
async def learn_delegation_voice(request: Request) -> VoiceOut:
    person = _caller(request)
    status = await gmail_status(person.email)
    if status != "connected":
        raise _refuse(409, _BLOCKING_CODES.get(status, "gmail_error"), STATUS_MESSAGES[status])
    try:
        stored = await learn_from_sent_mail(person, gmail_for(person.email or ""))
    except VoiceError as exc:
        raise _refuse(409, exc.code, exc.message) from exc
    except GmailAuthError as exc:
        raise _refuse(409, "gmail_needs_reconnect", STATUS_MESSAGES["needs_reconnect"]) from exc
    except GmailError as exc:
        logger.warning("delegation: learning the voice failed", exc_info=True)
        raise _refuse(502, "gmail_error", STATUS_MESSAGES["error"]) from exc
    return _voice_out(stored)


@router.post("/delegation/voice/signature", response_model=VoiceOut)
async def refresh_delegation_signature(request: Request) -> VoiceOut:
    """Read the signature from the caller's Gmail settings again and keep
    everything else, lock included: a relearn would replace their edits.
    Outlook has no signature an app can read, so it is refused there rather
    than clearing the one they have."""
    person = _caller(request)
    person_id = _person_id(person)
    if credential_provider(person.email or "") == "microsoft":
        raise _refuse(
            409, "signature_unavailable",
            "Outlook doesn't let apps read your signature, so drafts end with your sign-off.",
        )
    status = await gmail_status(person.email)
    if status != "connected":
        raise _refuse(409, _BLOCKING_CODES.get(status, "gmail_error"), STATUS_MESSAGES[status])
    try:
        signature = await gmail_for(person.email or "").send_as_signature()
    except GmailAuthError as exc:
        raise _refuse(409, "gmail_needs_reconnect", STATUS_MESSAGES["needs_reconnect"]) from exc
    except GmailError as exc:
        logger.warning("delegation: reading the Gmail signature failed", exc_info=True)
        raise _refuse(502, "gmail_error", STATUS_MESSAGES["error"]) from exc
    # Read after the Gmail call, so an edit made meanwhile is kept.
    stored = get_voice(person_id)
    profile, _ = validate_profile(
        {**asdict(stored.profile), "signature": signature}, allow_exemplars=True, keep_signature=True
    )
    saved = save_voice(person_id, profile, locked=stored.locked, updated_by=f"person:{person_id}")
    _audit(
        "delegation_voice_changed",
        f"Signature taken from Gmail settings by person {person_id}",
        {"op": "signature", "person_id": person_id, "has_signature": bool(profile.signature)},
    )
    return _voice_out(saved)


@router.post("/delegation/voice/describe", response_model=VoiceDescribedOut)
async def describe_delegation_voice(request: Request, body: VoiceDescribeIn) -> VoiceDescribedOut:
    """The caller's style from their own description, for them to review.
    Needs no mailbox: nothing is read or saved."""
    person = _caller(request)
    person_id = _person_id(person)
    try:
        described = await describe_voice(person_id, body.description)
    except VoiceError as exc:
        raise _refuse(409, exc.code, exc.message) from exc
    p = described.profile
    _audit(
        "delegation_voice_described",
        f"Writing style drafted from person {person_id}'s description",
        {"op": "describe", "person_id": person_id, "habits": len(p.habits), "dropped": described.dropped[:10]},
    )
    return VoiceDescribedOut(
        greetings=dict(p.greetings), sign_off=p.sign_off, length=p.length, formality=p.formality,
        habits=list(p.habits), avoid=list(p.avoid), sample_reply=described.sample_reply,
    )


@router.put("/delegation/voice", response_model=VoiceOut)
def update_delegation_voice(request: Request, body: VoiceUpdate) -> VoiceOut:
    person = _caller(request)
    person_id = _person_id(person)
    stored = get_voice(person_id)
    current = stored.profile
    sent = body.model_fields_set
    data: dict[str, Any] = {
        "greetings": body.greetings if "greetings" in sent and body.greetings is not None else current.greetings,
        "sign_off": body.sign_off if "sign_off" in sent and body.sign_off is not None else current.sign_off,
        "length": body.length if "length" in sent and body.length is not None else current.length,
        "formality": body.formality if "formality" in sent and body.formality is not None else current.formality,
        "habits": body.habits if "habits" in sent and body.habits is not None else current.habits,
        "avoid": body.avoid if "avoid" in sent and body.avoid is not None else current.avoid,
        "exemplars": [] if body.clear_exemplars else current.exemplars,
        "signature": "" if body.clear_signature else current.signature,
    }
    profile, dropped = validate_profile(data, allow_exemplars=True, keep_signature=True)
    # Anything the person just typed that did not pass is an error to show,
    # not something to drop silently.
    rejected = [
        d for d in dropped
        if d["field"].split(".")[0] in sent
    ]
    if rejected:
        fields = [d["field"].split(".")[0] for d in rejected]
        rules = dict.fromkeys(_VOICE_RULES[f] for f in fields if f in _VOICE_RULES)
        raise HTTPException(
            status_code=422,
            detail={
                "code": "invalid_voice",
                "message": "Some of it can't be saved: "
                + "; ".join(rules or ["write about how you write"])
                + ". No links, handles or amounts.",
                "rejected": rejected,
            },
        )
    for field in ("length", "formality"):
        if field in sent and getattr(body, field) and not getattr(profile, field):
            raise _refuse(422, "invalid_voice", f"{field} must be one of the listed values.")
    locked = body.locked if body.locked is not None else stored.locked
    saved = save_voice(person_id, profile, locked=locked, updated_by=f"person:{person_id}")
    _audit(
        "delegation_voice_changed",
        f"Writing profile edited by person {person_id}",
        {"op": "edit", "person_id": person_id, "fields": sorted(sent), "locked": locked},
    )
    return _voice_out(saved)


@router.delete("/delegation/voice", response_model=VoiceOut)
def reset_delegation_voice(request: Request) -> VoiceOut:
    person = _caller(request)
    person_id = _person_id(person)
    saved = reset_voice(person_id, updated_by=f"person:{person_id}")
    _audit(
        "delegation_voice_changed",
        f"Writing profile reset by person {person_id}",
        {"op": "reset", "person_id": person_id},
    )
    return _voice_out(saved)