Skip to content

gerodp/hermes-productivity-skills / travel/trip-planner

trip-planner

Verified

Plan a trip step by step: an itinerary plus a running budget that converts every currency into your preferred one, printed as two tables after each change — and a final summary with the budget broken down by category, the average spend per day, and checks for accommodation gaps and missing daily food/misc estimates.

FileKindSize
SKILL.mdskill md18.0 KB
scripts/render_trip.pyscript18.0 KB
scripts/test_render_trip.pyscript8.6 KB
scripts/test_trip_planner.pyscript31.4 KB
scripts/trip_planner.pyscript81.9 KB

scripts/trip_planner.py

View on GitHub
#!/usr/bin/env python3
"""trip-planner — plan a trip incrementally: itinerary + running budget.

You set the trip frame once (destination, dates, travelers, optional budget and
preferred currency), then add items one at a time — flights, stays, car rental,
excursions, meals, anything. After every change the tool re-prints the whole
itinerary and the budget table with a live total, converting any currency into
the trip's preferred one.

    check    Verify the state folder + FX sources (no secrets; there are none).
    new      Create a trip and make it active.
    list     List trips.  use    Switch the active trip.  set  Edit trip fields.
    add      Add an item (flight/stay/car/activity/...) — prints the tables.
    edit     Change an item.   rm   Remove an item.   undo  Restore the backup.
    show     Both tables (+ --json/--markdown/--html/--ics).
    itinerary / budget         Just one of the two tables.
    convert  Convert an amount.  rates  Show/refresh the FX cache.
    maps     Print Google Maps / Flights verification links (no network).

State lives in ~/.hermes/trips/ (override with --dir or an undeclared TRIP_DIR
in ~/.hermes/.env) — one JSON file per trip, never inside this repo.

NOTE: this skill is *not* a backward-looking report, so it deliberately does not
copy the shared local-time/Monday-start window vocabulary the report skills
share (it is excluded from tests/test_shared_window_vocab.py on purpose). Its
dates come from the trip itself.

Python standard library only — no third-party dependencies.
"""
from __future__ import annotations

import argparse
import json
import os
import re
import subprocess
import sys
import tempfile
import time
import unicodedata
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from datetime import date, datetime, timedelta, timezone
from decimal import Decimal, InvalidOperation

SCHEMA = 1
DEFAULT_DIR = "~/.hermes/trips"
ENV_DIR = "TRIP_DIR"  # intentionally NOT declared in SKILL.md (see CLAUDE.md #5)
HERMES_ENV = "~/.hermes/.env"
RATES_FILE = "_rates.json"
ACTIVE_FILE = "_active"
RATE_MAX_AGE = 24 * 3600  # refetch rates once a day
STALE_RATE_DAYS = 30      # warn when an item's frozen rate is older than this
HTTP_TIMEOUT = 15
USER_AGENT = "hermes-trip-planner/1.0 (+https://github.com/gerodp)"

# Control characters (except newline/tab) are stripped from text-mode output:
# titles, notes and links are free text and could carry terminal escapes that
# spoof or hide table rows. JSON output is safe as-is (escaped by json.dumps).
CONTROL_CHARS_RE = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]")

TYPES = ("flight", "stay", "lodging", "car", "activity", "meal", "transport", "other")
TYPE_EMOJI = {
    "flight": "✈️", "stay": "\U0001F3E8", "lodging": "\U0001F3E0",
    "car": "\U0001F697", "activity": "\U0001F39F️", "meal": "\U0001F37D️",
    "transport": "\U0001F68C", "other": "\U0001F4B3",
}
LODGING_TYPES = ("stay", "lodging")

# Budget breakdown categories: (key, item types, emoji). Order is the report order.
CATEGORIES = (
    ("flights", ("flight",), "✈️"),
    ("lodging", ("stay", "lodging"), "\U0001F3E8"),
    ("food", ("meal",), "\U0001F37D️"),
    ("activities", ("activity",), "\U0001F39F️"),
    ("transport", ("car", "transport"), "\U0001F697"),
    ("other", ("other",), "\U0001F4B3"),
)
TYPE_CATEGORY = {t: key for key, types, _ in CATEGORIES for t in types}

SYMBOLS = {"EUR": "€", "USD": "$", "GBP": "£", "JPY": "¥"}
SYMBOL_TO_CODE = {"€": "EUR", "$": "USD", "£": "GBP", "¥": "JPY"}

MONTHS = {
    "ene": 1, "enero": 1, "jan": 1, "january": 1,
    "feb": 2, "febrero": 2, "february": 2,
    "mar": 3, "marzo": 3, "march": 3,
    "abr": 4, "abril": 4, "apr": 4, "april": 4,
    "may": 5, "mayo": 5,
    "jun": 6, "junio": 6, "june": 6,
    "jul": 7, "julio": 7, "july": 7,
    "ago": 8, "agosto": 8, "aug": 8, "august": 8,
    "sep": 9, "set": 9, "sept": 9, "septiembre": 9, "september": 9,
    "oct": 10, "octubre": 10, "october": 10,
    "nov": 11, "noviembre": 11, "november": 11,
    "dic": 12, "diciembre": 12, "dec": 12, "december": 12,
}
MONTH_ABBR = {
    "es": ["ene", "feb", "mar", "abr", "may", "jun",
           "jul", "ago", "sep", "oct", "nov", "dic"],
    "en": ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
           "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
}

LABELS = {
    "es": {
        "itinerary": "ITINERARIO", "budget": "PRESUPUESTO",
        "date": "Fecha", "place": "Ciudad/Lugar", "activity": "Actividad/Estancia",
        "notes": "Notas", "link": "Enlace",
        "concept": "Concepto", "dates": "Fecha(s)", "amount": "Importe",
        "original": "Moneda Original", "total": "TOTAL PARCIAL",
        "budget_line": "Presupuesto", "spent": "Gastado", "remaining": "Restante",
        "per_person": "Por persona", "per_day": "Por día",
        "pending": "Por confirmar", "empty": "(sin elementos todavía)",
        "leg_out": "ida", "leg_back": "vuelta",
        "trip": "Viaje", "travelers": "Viajeros", "days": "días",
        "by_type": "Por categoría", "generated": "Generado",
        "summary": "RESUMEN DEL VIAJE", "breakdown": "DESGLOSE DEL PRESUPUESTO",
        "category": "Categoría", "share": "%", "per_day_col": "Por día",
        "per_person_col": "Por persona", "checks": "COMPROBACIONES",
        "questions": "PREGUNTAR AL USUARIO",
        "total_all": "TOTAL", "ready": "El plan está completo.",
        "avg_per_day": "Gasto medio por día",
        "avg_per_person_day": "Media por persona y día",
        "cat_flights": "Vuelos", "cat_lodging": "Alojamiento",
        "cat_food": "Comida", "cat_activities": "Actividades",
        "cat_transport": "Transporte", "cat_other": "Otros",
        "done_hint": ("Cuando termines de añadir gastos, dímelo (\"ya está\") y "
                      "preparo el resumen final: desglose por categoría, gasto "
                      "medio por día y revisión del viaje."),
    },
    "en": {
        "itinerary": "ITINERARY", "budget": "BUDGET",
        "date": "Date", "place": "City/Place", "activity": "Activity/Stay",
        "notes": "Notes", "link": "Link",
        "concept": "Concept", "dates": "Date(s)", "amount": "Amount",
        "original": "Original currency", "total": "SUBTOTAL",
        "budget_line": "Budget", "spent": "Spent", "remaining": "Remaining",
        "per_person": "Per person", "per_day": "Per day",
        "pending": "To confirm", "empty": "(no items yet)",
        "leg_out": "outbound", "leg_back": "return",
        "trip": "Trip", "travelers": "Travelers", "days": "days",
        "by_type": "By category", "generated": "Generated",
        "summary": "TRIP SUMMARY", "breakdown": "BUDGET BREAKDOWN",
        "category": "Category", "share": "%", "per_day_col": "Per day",
        "per_person_col": "Per person", "checks": "CHECKS",
        "questions": "ASK THE USER",
        "total_all": "TOTAL", "ready": "The plan is complete.",
        "avg_per_day": "Average spend per day",
        "avg_per_person_day": "Average per person per day",
        "cat_flights": "Flights", "cat_lodging": "Lodging",
        "cat_food": "Food", "cat_activities": "Activities",
        "cat_transport": "Transport", "cat_other": "Other",
        "done_hint": ("When you have finished adding expenses, tell me "
                      "(\"that's everything\") and I'll produce the final "
                      "summary: breakdown by category, average spend per day "
                      "and a review of the trip."),
    },
}


class TripError(Exception):
    """User-facing error — the message is safe to print (never holds secrets)."""


def sanitize_text(s):
    return CONTROL_CHARS_RE.sub("", s or "")


# --------------------------------------------------------------------------- #
# Display width (emoji are double-width but len()==1)
# --------------------------------------------------------------------------- #
def _char_width(ch):
    if ch in ("️", "︎", "‍") or unicodedata.combining(ch):
        return 0
    o = ord(ch)
    if 0x1F000 <= o <= 0x1FAFF or 0x2600 <= o <= 0x27BF:
        return 2
    return 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1


def dwidth(s):
    return sum(_char_width(c) for c in s)


def dljust(s, w):
    return s + " " * max(0, w - dwidth(s))


def drjust(s, w):
    return " " * max(0, w - dwidth(s)) + s


def dtrunc(s, w):
    if w <= 0 or dwidth(s) <= w:
        return s
    out, used = [], 0
    for ch in s:
        cw = _char_width(ch)
        if used + cw > w - 1:
            break
        out.append(ch)
        used += cw
    return "".join(out) + "…"


# --------------------------------------------------------------------------- #
# Config / paths
# --------------------------------------------------------------------------- #
def _env_file_value(name, path=HERMES_ENV):
    """Read KEY=VALUE from ~/.hermes/.env — for vars Hermes does not inject.

    Declaring an optional override in SKILL.md would make Hermes prompt for it
    (CLAUDE.md gotcha #5), so TRIP_DIR is read here instead.
    """
    try:
        with open(os.path.expanduser(path), "r", encoding="utf-8") as fh:
            for line in fh:
                line = line.strip()
                if not line or line.startswith("#") or "=" not in line:
                    continue
                k, v = line.split("=", 1)
                if k.strip() == name:
                    return v.strip().strip("'\"") or None
    except OSError:
        return None
    return None


def resolve_dir(explicit=None, env=None, create=True):
    env = os.environ if env is None else env
    raw = explicit or env.get(ENV_DIR) or _env_file_value(ENV_DIR) or DEFAULT_DIR
    path = os.path.expanduser(raw)
    if create:
        try:
            os.makedirs(path, exist_ok=True)
        except OSError as e:
            raise TripError(f"cannot create the trips folder {path}: {e.strerror}")
    if not os.path.isdir(path):
        raise TripError(f"trips folder not found: {path}")
    return os.path.realpath(path)


SLUG_OK_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")


def slugify(name):
    s = unicodedata.normalize("NFKD", name or "")
    s = "".join(c for c in s if not unicodedata.combining(c))
    s = re.sub(r"[^a-zA-Z0-9]+", "-", s).strip("-").lower()
    s = re.sub(r"-{2,}", "-", s)[:64].strip("-")
    if not s:
        raise TripError("could not derive a trip name — pass --slug with letters/digits")
    return s


def trip_path(base, slug):
    """Absolute path of a trip file, contained under `base` on every branch."""
    if not SLUG_OK_RE.match(slug or ""):
        raise TripError(
            f"invalid trip id {slug!r} — use lowercase letters, digits and dashes")
    p = os.path.join(base, slug + ".json")
    rp = os.path.realpath(p)
    if os.path.commonpath([rp, base]) != base:
        raise TripError(f"refusing to use a path outside the trips folder: {slug}")
    return rp


def atomic_write(path, text, backup=True):
    d = os.path.dirname(path)
    if backup and os.path.exists(path):
        try:
            with open(path, "r", encoding="utf-8") as fh:
                prev = fh.read()
            atomic_write(path + ".bak", prev, backup=False)
        except OSError:
            pass
    fd, tmp = tempfile.mkstemp(dir=d, prefix=".tmp-trip-")
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as fh:
            fh.write(text)
        os.replace(tmp, path)
    except BaseException:
        try:
            os.unlink(tmp)
        except OSError:
            pass
        raise


# --------------------------------------------------------------------------- #
# Dates — tolerant es/en parsing ("13 ago", "13-16 ago", "13/08", ISO)
# --------------------------------------------------------------------------- #
DAY_MONTH_RE = re.compile(
    r"^(\d{1,2})\s*(?:de\s+)?([a-záéíóú]{3,12})\.?"
    r"(?:\s*(?:de\s+)?(\d{4}))?$")
MONTH_DAY_RE = re.compile(
    r"^([a-záéíóú]{3,12})\.?\s+(\d{1,2})"
    r"(?:\s*,?\s*(\d{4}))?$")
NUMERIC_RE = re.compile(r"^(\d{1,2})[/.](\d{1,2})(?:[/.](\d{2,4}))?$")
ISO_RE = re.compile(r"^(\d{4})-(\d{1,2})-(\d{1,2})$")
DAY_RANGE_RE = re.compile(
    r"^(\d{1,2})\s*[-–—]\s*(\d{1,2})\s*(?:de\s+)?"
    r"([a-záéíóú]{3,12})\.?(?:\s*(?:de\s+)?(\d{4}))?$")


def _month_number(word):
    w = unicodedata.normalize("NFKD", word.lower())
    w = "".join(c for c in w if not unicodedata.combining(c)).rstrip(".")
    return MONTHS.get(w)


def _mk_date(y, m, d):
    try:
        return date(y, m, d)
    except ValueError:
        raise TripError(f"not a real date: {y:04d}-{m:02d}-{d:02d}")


def _infer_year(month, day, ref):
    """Pick the year for a date given without one, relative to `ref`."""
    ref = ref or date.today()
    cand = _mk_date(ref.year, month, day)
    if cand < ref - timedelta(days=180):
        cand = _mk_date(ref.year + 1, month, day)
    return cand


def parse_date(text, ref=None):
    """Parse one date. Accepts ISO, 13/08, '13 ago', 'ago 13', '13 de agosto'."""
    if isinstance(text, date):
        return text
    s = sanitize_text(str(text or "")).strip().lower().replace("\u00a0", " ")
    s = re.sub(r"\s+", " ", s)
    if not s:
        raise TripError("empty date")
    if s in ("hoy", "today"):
        return date.today()
    if s in ("manana", "mañana", "tomorrow"):
        return date.today() + timedelta(days=1)
    m = ISO_RE.match(s)
    if m:
        return _mk_date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
    m = NUMERIC_RE.match(s)
    if m:
        day, mon = int(m.group(1)), int(m.group(2))
        if m.group(3):
            y = int(m.group(3))
            return _mk_date(y + 2000 if y < 100 else y, mon, day)
        return _infer_year(mon, day, ref)
    m = DAY_MONTH_RE.match(s)
    if m and _month_number(m.group(2)):
        day, mon = int(m.group(1)), _month_number(m.group(2))
        if m.group(3):
            return _mk_date(int(m.group(3)), mon, day)
        return _infer_year(mon, day, ref)
    m = MONTH_DAY_RE.match(s)
    if m and _month_number(m.group(1)):
        mon, day = _month_number(m.group(1)), int(m.group(2))
        if m.group(3):
            return _mk_date(int(m.group(3)), mon, day)
        return _infer_year(mon, day, ref)
    raise TripError(
        f"could not read the date {text!r} — use YYYY-MM-DD, 13/08, "
        "'13 ago' or '13 aug'")


def parse_date_range(text, ref=None):
    """Parse a single date or a range → (start, end). '13-16 ago', '13 ago'."""
    s = sanitize_text(str(text or "")).strip().lower().replace("\u00a0", " ")
    s = re.sub(r"\s+", " ", s)
    if not s:
        raise TripError("empty date")
    m = DAY_RANGE_RE.match(s)
    if m and _month_number(m.group(3)):
        mon, year = _month_number(m.group(3)), m.group(4)
        d1, d2 = int(m.group(1)), int(m.group(2))
        if year:
            return _mk_date(int(year), mon, d1), _mk_date(int(year), mon, d2)
        a = _infer_year(mon, d1, ref)
        return a, _mk_date(a.year, mon, d2)
    for sep in ("..", " a ", " to ", " al ", "–", "—"):
        if sep in s:
            left, _, right = s.partition(sep)
            a = parse_date(left, ref)
            return a, parse_date(right, a)
    if "-" in s and not ISO_RE.match(s):
        left, _, right = s.partition("-")
        try:
            a = parse_date(left, ref)
            return a, parse_date(right, a)
        except TripError:
            pass
    d = parse_date(s, ref)
    return d, d


def fmt_day(d, lang="es"):
    return f"{d.day} {MONTH_ABBR[lang][d.month - 1]}"


def fmt_span(start, end, lang="es"):
    """'13 ago' / '13-16 ago' / '31 ago - 2 sep' — the itinerary date cell."""
    if not start:
        return "—"
    if not end or end == start:
        return fmt_day(start, lang)
    dash = "-" if lang == "es" else "–"
    if start.month == end.month and start.year == end.year:
        return f"{start.day}{dash}{end.day} {MONTH_ABBR[lang][start.month - 1]}"
    return f"{fmt_day(start, lang)} {dash} {fmt_day(end, lang)}"


# --------------------------------------------------------------------------- #
# Money — tolerant parsing ("2.450.000 COP", "420 USD", "2.480,00 €", "$630")
# --------------------------------------------------------------------------- #
CODE_RE = re.compile(r"\b([A-Za-z]{3})\b")


def parse_amount(text, default_currency=None):
    """Return (Decimal, currency_code_or_None). Currency may come from the text."""
    if text is None:
        raise TripError("no amount given")
    s = sanitize_text(str(text)).strip().replace("\u00a0", " ")
    if not s:
        raise TripError("no amount given")
    currency = None
    for sym, code in SYMBOL_TO_CODE.items():
        if sym in s:
            currency = code
            s = s.replace(sym, " ")
    m = CODE_RE.search(s)
    if m:
        cand = m.group(1).upper()
        if cand.isalpha():
            currency = cand
            s = (s[:m.start()] + " " + s[m.end():])
    s = s.strip().replace(" ", "")
    if not s:
        raise TripError(f"no number found in the amount {text!r}")
    neg = s.startswith("-")
    s = s.lstrip("+-")
    if not re.fullmatch(r"[\d.,]+", s):
        raise TripError(
            f"could not read the amount {text!r} — try 630, '420 USD' or "
            "'2.450.000 COP'")
    if "," in s and "." in s:
        dec = "," if s.rfind(",") > s.rfind(".") else "."
        s = s.replace("." if dec == "," else ",", "").replace(dec, ".")
    elif "," in s or "." in s:
        sep = "," if "," in s else "."
        parts = s.split(sep)
        tail = parts[-1]
        # 2.450.000 / 1,500 → grouping; 420,50 / 1.5 → decimal
        if len(parts) > 2 or (len(tail) == 3 and len(parts[0]) <= 3):
            s = s.replace(sep, "")
        else:
            s = s.replace(sep, ".")
    try:
        value = Decimal(s)
    except InvalidOperation:
        raise TripError(f"could not read the amount {text!r}")
    if neg:
        value = -value
    return value, (currency or (default_currency.upper() if default_currency else None))


def fmt_money(value, currency, lang="es"):
    n = f"{float(value):,.2f}"
    if lang == "es":
        n = n.replace(",", "\x00").replace(".", ",").replace("\x00", ".")
    sym = SYMBOLS.get(currency)
    return f"{n} {sym}" if sym and currency in ("EUR", "USD", "GBP", "JPY") \
        else f"{n} {currency}"


def fmt_rate(rate, frm, to, lang="es"):
    # "1 COP = 0,0003 EUR" is unreadable — state tiny rates the other way round.
    if 0 < float(rate) < 0.01:
        return fmt_rate(1.0 / float(rate), to, frm, lang)
    r = f"{float(rate):,.4f}".rstrip("0").rstrip(".")
    if lang == "es":
        r = r.replace(",", "\x00").replace(".", ",").replace("\x00", ".")
    return f"1 {frm} = {r} {to}"


def q2(value):
    return float(Decimal(value).quantize(Decimal("0.01")))


# --------------------------------------------------------------------------- #
# FX rates — ECB → open.er-api → floatrates, cached 24h, EUR-based
# --------------------------------------------------------------------------- #
ECB_URL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
ERAPI_URL = "https://open.er-api.com/v6/latest/EUR"
FLOAT_URL = "https://www.floatrates.com/daily/eur.json"


LAST_TRANSPORT = None  # "urllib" | "curl" — which one actually fetched, for `check`


def http_get(url, timeout=HTTP_TIMEOUT):
    """GET a URL as text. Falls back to `curl` when urllib's TLS is unusable.

    Hermes' python3 can resolve to an interpreter with a broken `ssl` module
    (CLAUDE.md gotcha #2), where urllib raises "unknown url type: https".
    """
    req = urllib.request.Request(url, headers={
        "Accept": "application/json, application/xml;q=0.9, */*;q=0.8",
        "User-Agent": USER_AGENT,
    })
    global LAST_TRANSPORT
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            data = resp.read().decode("utf-8", "replace")
        LAST_TRANSPORT = "urllib"
        return data
    except urllib.error.HTTPError as e:
        raise TripError(f"HTTP {e.code} from {url.split('?')[0]}")
    except Exception:
        pass  # fall through to curl
    try:
        out = subprocess.run(
            ["curl", "-sS", "--max-time", str(timeout), "-A", USER_AGENT, url],
            capture_output=True, text=True, timeout=timeout + 5)
    except (OSError, subprocess.TimeoutExpired):
        raise TripError(f"cannot reach {url.split('?')[0]} (no network?)")
    if out.returncode != 0 or not out.stdout.strip():
        raise TripError(f"cannot reach {url.split('?')[0]} (no network?)")
    LAST_TRANSPORT = "curl"
    return out.stdout


def parse_ecb(text):
    root = ET.fromstring(text)
    rates, day = {"EUR": 1.0}, None
    for cube in root.iter():
        tag = cube.tag.rsplit("}", 1)[-1]
        if tag != "Cube":
            continue
        if cube.get("time"):
            day = cube.get("time")
        cur, rate = cube.get("currency"), cube.get("rate")
        if cur and rate:
            try:
                rates[cur.upper()] = float(rate)
            except ValueError:
                continue
    if len(rates) < 5:
        raise TripError("unexpected ECB response")
    return rates, day


def parse_erapi(text):
    payload = json.loads(text)
    if payload.get("result") != "success" or not payload.get("rates"):
        raise TripError("unexpected open.er-api response")
    rates = {k.upper(): float(v) for k, v in payload["rates"].items()
             if isinstance(v, (int, float))}
    rates["EUR"] = 1.0
    day = (payload.get("time_last_update_utc") or "")[5:16].strip()
    return rates, day or None


def parse_floatrates(text):
    payload = json.loads(text)
    rates = {"EUR": 1.0}
    for row in payload.values():
        code, rate = (row.get("code") or "").upper(), row.get("rate")
        if code and rate:
            try:
                rates[code] = float(rate)
            except (TypeError, ValueError):
                continue
    if len(rates) < 5:
        raise TripError("unexpected floatrates response")
    return rates, None


SOURCES = (("ecb", ECB_URL, parse_ecb),
           ("er-api", ERAPI_URL, parse_erapi),
           ("floatrates", FLOAT_URL, parse_floatrates))


def rates_path(base):
    return os.path.join(base, RATES_FILE)


def read_rate_cache(base):
    try:
        with open(rates_path(base), "r", encoding="utf-8") as fh:
            cache = json.load(fh)
        if isinstance(cache, dict) and cache.get("rates"):
            return cache
    except (OSError, ValueError):
        pass
    return None


def load_rates(base, need=None, refresh=False, now=None, getter=None):
    """Return the EUR-based rate table, fetching/merging sources as needed.

    `need` is a currency that must be present — ECB alone does not carry every
    currency (no COP, for instance), so the next source is tried until it is.
    Returns a dict: {rates, sources, fetched_at, date, stale}.
    """
    now = time.time() if now is None else now
    getter = getter or http_get
    wanted = [need] if isinstance(need, str) else list(need or [])
    wanted = [c.upper() for c in wanted if c]
    need = wanted[0] if wanted else None

    def complete(rates):
        return all(c in rates for c in wanted)

    cache = read_rate_cache(base)
    if cache and not refresh:
        fresh = (now - float(cache.get("fetched_at") or 0)) < RATE_MAX_AGE
        if fresh and complete(cache["rates"]):
            cache["stale"] = False
            return cache

    rates, sources, day, errors = {}, [], None, []
    for name, url, parser in SOURCES:
        try:
            fetched, fday = parser(getter(url))
        except (TripError, ValueError, ET.ParseError) as e:
            errors.append(f"{name}: {e}")
            continue
        for code, value in fetched.items():
            rates.setdefault(code, value)
        sources.append(name)
        day = day or fday
        if complete(rates):
            break
    if rates and complete(rates):
        cache = {"base": "EUR", "rates": rates, "sources": sources,
                 "fetched_at": now, "date": day or date.today().isoformat(),
                 "transport": LAST_TRANSPORT, "stale": False}
        try:
            atomic_write(rates_path(base), json.dumps(cache, sort_keys=True),
                         backup=False)
        except OSError:
            pass
        return cache
    if cache and complete(cache["rates"]):
        cache["stale"] = True
        return cache
    detail = "; ".join(errors) if errors else "no rate source returned data"
    missing = [c for c in wanted if c not in rates]
    if rates and missing:
        need = missing[0]
        raise TripError(
            f"unknown currency {need!r} — no rate source lists it. Pass the rate "
            f"yourself: --rate <1 {need} in your trip currency>. Look it up at "
            f"https://www.google.com/search?q=1+{urllib.parse.quote(need)}+to+EUR")
    raise TripError(
        "could not fetch exchange rates (" + detail + "). Add the item with an "
        "explicit rate instead: --rate <value>. Look the rate up at "
        "https://www.google.com/search?q=" +
        urllib.parse.quote(f"1 {need or 'USD'} to EUR"))


def cross_rate(rates, frm, to):
    """How many units of `to` one unit of `frm` buys (EUR-based table)."""
    frm, to = frm.upper(), to.upper()
    for code in (frm, to):
        if code not in rates:
            raise TripError(
                f"no exchange rate for {code} — pass --rate explicitly "
                f"(https://www.google.com/search?q=1+{code}+to+EUR)")
    return rates[to] / rates[frm]


# --------------------------------------------------------------------------- #
# Trip documents
# --------------------------------------------------------------------------- #
def active_path(base):
    return os.path.join(base, ACTIVE_FILE)


def get_active(base):
    try:
        with open(active_path(base), "r", encoding="utf-8") as fh:
            slug = fh.read().strip()
        return slug or None
    except OSError:
        return None


def set_active(base, slug):
    atomic_write(active_path(base), slug + "\n", backup=False)


def list_trips(base):
    out = []
    for fn in sorted(os.listdir(base)):
        if not fn.endswith(".json") or fn.startswith("_") or fn.startswith("."):
            continue
        try:
            out.append(read_trip(base, fn[:-5]))
        except TripError:
            continue
    out.sort(key=lambda t: (t.get("start") or "", t["slug"]))
    return out


def read_trip(base, slug):
    path = trip_path(base, slug)
    try:
        with open(path, "r", encoding="utf-8") as fh:
            doc = json.load(fh)
    except FileNotFoundError:
        raise TripError(
            f"trip {slug!r} not found — run `list` to see them, or `new` to "
            "create one")
    except ValueError:
        raise TripError(f"trip file is corrupted: {path} (try `undo`)")
    doc.setdefault("items", [])
    doc.setdefault("lang", "es")
    doc.setdefault("currency", "EUR")
    doc["slug"] = slug
    return doc


def write_trip(base, doc):
    doc["updated"] = date.today().isoformat()
    atomic_write(trip_path(base, doc["slug"]),
                 json.dumps(doc, indent=2, ensure_ascii=False, sort_keys=True))


def resolve_trip(base, slug=None):
    slug = slug or get_active(base)
    if not slug:
        trips = list_trips(base)
        if len(trips) == 1:
            return trips[0]
        if not trips:
            raise TripError(
                "no trip yet — create one first: new --name NAME --destination "
                "PLACE --start YYYY-MM-DD --end YYYY-MM-DD --travelers N")
        raise TripError("several trips exist — pick one with `use <id>` or --trip <id>")
    return read_trip(base, slug)


def next_id(doc):
    nid = int(doc.get("next_id") or 0)
    if not nid:
        nid = max([int(i.get("id") or 0) for i in doc["items"]] or [0]) + 1
    doc["next_id"] = nid + 1
    return nid


def find_item(doc, item_id):
    try:
        wanted = int(item_id)
    except (TypeError, ValueError):
        raise TripError(f"item id must be a number, got {item_id!r}")
    for item in doc["items"]:
        if int(item.get("id") or 0) == wanted:
            return item
    raise TripError(f"no item with id {wanted} — run `show` to see the ids")


def item_days(item):
    """Days an item spans, inclusive — the multiplier behind --per-day."""
    if not item.get("start"):
        return 1
    a = date.fromisoformat(item["start"])
    b = date.fromisoformat(item.get("end") or item["start"])
    return max(1, (b - a).days + 1)


def trip_days(doc):
    if not doc.get("start") or not doc.get("end"):
        return 0
    a = date.fromisoformat(doc["start"])
    b = date.fromisoformat(doc["end"])
    return max(1, (b - a).days + 1)


# --------------------------------------------------------------------------- #
# Item construction
# --------------------------------------------------------------------------- #
def _clean_link(link):
    if not link:
        return ""
    link = sanitize_text(link).strip()
    if not link:
        return ""
    if not re.match(r"^https?://", link, re.I):
        raise TripError("--link must start with http:// or https://")
    return link


ROUTE_SPLIT_RE = re.compile(r"\s*(?:→|⇄|->|<->|–|—|/| - |-)\s*")


def parse_route(place):
    """Pull (origin, destination) out of a free-text place like 'Ciudad Sur → Ciudad Norte'."""
    parts = [p.strip() for p in ROUTE_SPLIT_RE.split(sanitize_text(place or ""))
             if p.strip()]
    return (parts[0], parts[1]) if len(parts) >= 2 else (None, None)


def flight_place(origin, destination, roundtrip):
    return f"{origin} {'⇄' if roundtrip else '→'} {destination}"


def _clean_link_soft(link):
    """Like _clean_link but drops a bad link instead of raising (render path)."""
    try:
        return _clean_link(link)
    except TripError:
        return ""


def _read_notes(args):
    if getattr(args, "notes_file", None):
        try:
            with open(os.path.expanduser(args.notes_file), "r", encoding="utf-8") as fh:
                return fh.read().strip()
        except OSError as e:
            raise TripError(f"cannot read --notes-file: {e.strerror}")
    return (getattr(args, "notes", None) or "").strip()


def apply_item_fields(item, args, doc, base, *, creating, getter=None):
    """Fill/patch an item from CLI args. Money is converted and *frozen*."""
    ref = date.fromisoformat(doc["start"]) if doc.get("start") else None

    if getattr(args, "type", None):
        if args.type not in TYPES:
            raise TripError(f"--type must be one of: {', '.join(TYPES)}")
        item["type"] = args.type
    if creating:
        item.setdefault("type", "other")
    if getattr(args, "title", None):
        item["title"] = sanitize_text(args.title).strip()
    if creating and not item.get("title"):
        raise TripError("--title is required (what is this item?)")
    if getattr(args, "place", None) is not None:
        item["place"] = sanitize_text(args.place).strip()
    if getattr(args, "link", None) is not None:
        item["link"] = _clean_link(args.link)
    notes = _read_notes(args)
    if notes or getattr(args, "notes", None) is not None:
        item["notes"] = sanitize_text(notes)
    if getattr(args, "status", None):
        item["status"] = args.status
    item.setdefault("status", "confirmed")
    item.setdefault("notes", "")
    item.setdefault("place", "")
    item.setdefault("link", "")

    # ---- dates
    if getattr(args, "date", None):
        s, e = parse_date_range(args.date, ref)
        item["start"], item["end"] = s.isoformat(), e.isoformat()
    if getattr(args, "start", None):
        item["start"] = parse_date(args.start, ref).isoformat()
    if getattr(args, "end", None):
        item["end"] = parse_date(
            args.end, date.fromisoformat(item["start"]) if item.get("start") else ref
        ).isoformat()
    if creating and not item.get("start"):
        raise TripError(
            "no date — pass --date '13 ago' (or --start/--end for a range)")

    # ---- flights: the route and the direction must be explicit, never guessed
    if getattr(args, "origin", None):
        item["origin"] = sanitize_text(args.origin).strip()
    if getattr(args, "destination", None):
        item["destination"] = sanitize_text(args.destination).strip()
    if getattr(args, "roundtrip", False):
        item["roundtrip"] = True
    elif getattr(args, "one_way", False):
        item["roundtrip"] = False
    if item.get("type") == "flight":
        if not (item.get("origin") and item.get("destination")):
            o, d = parse_route(item.get("place"))
            item["origin"] = item.get("origin") or o
            item["destination"] = item.get("destination") or d
        if creating and not (item.get("origin") and item.get("destination")):
            raise TripError(
                "a flight needs its route — ask the user where it departs from "
                "and where it lands, then pass --from MAD --to BOG (or "
                "--place 'Ciudad Sur → Ciudad Norte'). Ask in the same message whether it "
                "is one-way (--one-way) or a return flight (--roundtrip).")
        if creating and item.get("roundtrip") is None:
            raise TripError(
                "is this flight one-way or a return? Ask the user, then pass "
                "--one-way or --roundtrip (for a return flight also give the "
                "return date with --end).")
        if item.get("origin") and item.get("destination"):
            item["place"] = flight_place(item["origin"], item["destination"],
                                         item.get("roundtrip"))
    item.setdefault("roundtrip", None)
    if item.get("end") and item.get("start") and item["end"] < item["start"]:
        raise TripError("the item's end date is before its start date")
    item.setdefault("end", item.get("start"))

    # ---- money
    if getattr(args, "qty", None) is not None:
        if args.qty < 1:
            raise TripError("--qty must be 1 or more")
        item["qty"] = int(args.qty)
    item.setdefault("qty", 1)
    if getattr(args, "per_person", False):
        item["per_person"] = True
    item.setdefault("per_person", False)
    if getattr(args, "per_day", False):
        item["per_day"] = True
    item.setdefault("per_day", False)

    amount_given = getattr(args, "amount", None) is not None
    if amount_given:
        value, currency = parse_amount(args.amount,
                                       getattr(args, "currency", None) or doc["currency"])
        if getattr(args, "currency", None):
            currency = args.currency.upper()
        item["amount"] = float(value)
        item["currency"] = currency
    elif getattr(args, "currency", None) and item.get("amount") is not None:
        item["currency"] = args.currency.upper()

    if item.get("amount") is not None:
        recost(item, doc, base, rate=getattr(args, "rate", None), getter=getter)
    else:
        item.setdefault("amount", None)
        item.setdefault("currency", None)
        item.setdefault("total", None)
        item.setdefault("converted", None)
    return item


def recost(item, doc, base, rate=None, getter=None, rates_ctx=None):
    """(Re)compute an item's converted total, freezing the rate used."""
    trip_cur = doc["currency"].upper()
    cur = (item.get("currency") or trip_cur).upper()
    item["currency"] = cur
    units = Decimal(str(item["amount"])) * item.get("qty", 1)
    if item.get("per_person"):
        units *= int(doc.get("travelers") or 1)
    if item.get("per_day"):
        units *= item_days(item)
    item["total"] = q2(units)
    if cur == trip_cur:
        item.update(rate=1.0, rate_date=date.today().isoformat(),
                    rate_source="same-currency", converted=q2(units))
        return item
    if rate is not None:
        used, source, day = float(rate), "manual", date.today().isoformat()
    else:
        # both sides must be in the table — the trip currency can be the exotic
        # one (a COP-based trip paying a USD invoice)
        ctx = rates_ctx or load_rates(base, need=[cur, trip_cur], getter=getter)
        used = cross_rate(ctx["rates"], cur, trip_cur)
        source = "+".join(ctx.get("sources") or []) or "cache"
        day = ctx.get("date") or date.today().isoformat()
        if ctx.get("stale"):
            source += " (cached)"
    item.update(rate=used, rate_source=source, rate_date=day,
                converted=q2(units * Decimal(str(used))))
    return item


def is_duplicate(doc, item):
    for other in doc["items"]:
        if other is item:
            continue
        if (other.get("type") == item.get("type")
                and (other.get("title") or "").lower() == (item.get("title") or "").lower()
                and other.get("start") == item.get("start")
                and other.get("total") == item.get("total")):
            return other
    return None


# --------------------------------------------------------------------------- #
# Warnings
# --------------------------------------------------------------------------- #
def _night_set(start, end):
    """Nights covered by a stay: check-in .. check-out - 1."""
    if not start:
        return set()
    a = date.fromisoformat(start)
    b = date.fromisoformat(end or start)
    if b <= a:
        return {a}
    return {a + timedelta(days=n) for n in range((b - a).days)}


def _fmt_night_gaps(nights, lang):
    out, run = [], []
    for day in sorted(nights):
        if run and day == run[-1] + timedelta(days=1):
            run.append(day)
        else:
            if run:
                out.append(run)
            run = [day]
    if run:
        out.append(run)
    return ", ".join(fmt_span(r[0], r[-1] + timedelta(days=1) if len(r) > 1 else None, lang)
                     for r in out)


def build_warnings(doc, lang, today=None):
    today = today or date.today()
    w = []
    start = date.fromisoformat(doc["start"]) if doc.get("start") else None
    end = date.fromisoformat(doc["end"]) if doc.get("end") else None
    es = lang == "es"
    items = doc["items"]

    if start and end:
        covered = set()
        stays = [i for i in items if i.get("type") in LODGING_TYPES]
        for i in stays:
            covered |= _night_set(i.get("start"), i.get("end"))
        wanted = {start + timedelta(days=n) for n in range((end - start).days)}
        missing = wanted - covered
        if missing and stays:
            w.append(("Sin alojamiento: " if es else "No lodging booked: ")
                     + _fmt_night_gaps(missing, lang)
                     + (f" ({len(missing)} noches)" if es else f" ({len(missing)} nights)"))
        elif not stays:
            w.append("Aún no hay alojamiento en el viaje."
                     if es else "No lodging added to the trip yet.")
        for a in range(len(stays)):
            for b in range(a + 1, len(stays)):
                if _night_set(stays[a].get("start"), stays[a].get("end")) & \
                        _night_set(stays[b].get("start"), stays[b].get("end")):
                    w.append((f"Alojamientos solapados: {stays[a]['title']} y "
                              f"{stays[b]['title']}") if es else
                             (f"Overlapping stays: {stays[a]['title']} and "
                              f"{stays[b]['title']}"))
        for i in items:
            if not i.get("start"):
                continue
            if date.fromisoformat(i["start"]) < start or \
                    date.fromisoformat(i.get("end") or i["start"]) > end:
                w.append((f"Fuera de las fechas del viaje: {i['title']}" if es else
                          f"Outside the trip dates: {i['title']}"))

    for i in items:
        if i.get("type") == "flight" and i.get("roundtrip") and \
                i.get("end") == i.get("start"):
            w.append((f"Vuelo de ida y vuelta sin fecha de regreso: {i['title']}"
                      if es else f"Return flight with no return date: {i['title']}"))

    pending = [i for i in items if i.get("status") == "pending"]
    if pending:
        w.append(("Pendiente de confirmar: " if es else "Still to confirm: ")
                 + ", ".join(i["title"] for i in pending))
    no_amount = [i for i in items if i.get("total") is None]
    if no_amount:
        w.append(("Sin importe: " if es else "No amount yet: ")
                 + ", ".join(i["title"] for i in no_amount))

    spent = sum(i.get("converted") or 0 for i in items)
    budget = doc.get("budget")
    if budget:
        if spent > budget:
            over = fmt_money(spent - budget, doc["currency"], lang)
            w.append((f"Presupuesto superado en {over}" if es else
                      f"Over budget by {over}"))
        elif spent > 0.9 * budget:
            w.append("Cerca del límite del presupuesto (>90%)" if es else
                     "Close to the budget limit (>90%)")
    for i in items:
        if i.get("rate_date") and i.get("rate_source") not in (None, "same-currency"):
            try:
                age = (today - date.fromisoformat(i["rate_date"])).days
            except ValueError:
                continue
            if age > STALE_RATE_DAYS:
                w.append((f"Tipo de cambio antiguo ({age} días) en {i['title']}"
                          if es else
                          f"Exchange rate is {age} days old for {i['title']}"))
    return w


# --------------------------------------------------------------------------- #
# Final-review helpers: category breakdown + readiness checks
# --------------------------------------------------------------------------- #
def build_breakdown(items, currency, lang, days, travelers, spent):
    """One row per budget category, with its share, per-day and per-person cost."""
    rows = []
    for key, types, emoji in CATEGORIES:
        amount = round(sum(i.get("converted") or 0
                           for i in items if i.get("type") in types), 2)
        if not amount:
            continue
        rows.append({
            "key": key, "emoji": emoji, "label": LABELS[lang][f"cat_{key}"],
            "amount": amount,
            "pct": round(100.0 * amount / spent, 1) if spent else 0.0,
            "per_day": round(amount / days, 2) if days else None,
            "per_person": round(amount / travelers, 2) if travelers else None,
            "display": {
                "amount": fmt_money(amount, currency, lang),
                "per_day": fmt_money(amount / days, currency, lang) if days else "—",
                "per_person": fmt_money(amount / travelers, currency, lang)
                if travelers else "—",
            },
        })
    return rows


def build_checks(doc, lang):
    """What still has to be settled before the trip plan can be called done."""
    es = lang == "es"
    items = doc["items"]
    start = date.fromisoformat(doc["start"]) if doc.get("start") else None
    end = date.fromisoformat(doc["end"]) if doc.get("end") else None
    span = (f'--start {doc.get("start")} --end {doc.get("end")}'
            if doc.get("start") else "--date <fechas>")

    nights_total, covered = 0, set()
    if start and end:
        wanted = {start + timedelta(days=n) for n in range((end - start).days)}
        nights_total = len(wanted)
        for i in items:
            if i.get("type") in LODGING_TYPES:
                covered |= _night_set(i.get("start"), i.get("end")) & wanted
    missing = nights_total - len(covered)
    gaps, gap_span = "", span
    if start and end and missing:
        gap_nights = {start + timedelta(days=n)
                      for n in range((end - start).days)} - covered
        gaps = _fmt_night_gaps(gap_nights, lang)
        # Point the suggested command at the FIRST gap, not the whole trip:
        # check-in on the first uncovered night, check-out the morning after the
        # last consecutive one.
        first = min(gap_nights)
        last = first
        while last + timedelta(days=1) in gap_nights:
            last += timedelta(days=1)
        gap_span = (f"--start {first.isoformat()} "
                    f"--end {(last + timedelta(days=1)).isoformat()}")

    has_food = any(i.get("type") == "meal" for i in items)
    has_misc = any(i.get("type") == "other" for i in items)
    daily_food = any(i.get("type") == "meal" and i.get("per_day") for i in items)
    daily_misc = any(i.get("type") == "other" and i.get("per_day") for i in items)

    questions = []
    if missing:
        questions.append({
            "key": "lodging",
            "text": (f"Faltan {missing} noche(s) sin alojamiento ({gaps}). "
                     "¿Dónde dormiréis esas noches?" if es else
                     f"{missing} night(s) have no accommodation ({gaps}). "
                     "Where are you staying then?"),
            "command": (f'add --type stay --title "<hotel>" {gap_span} '
                        "--amount <importe>"),
        })
    if not has_food:
        questions.append({
            "key": "food",
            "text": ("No hay ninguna estimación de comidas. ¿Cuánto calculáis al "
                     "día por persona para comer?" if es else
                     "There is no food estimate yet. How much per person per day "
                     "do you budget for meals?"),
            "command": (f'add --type meal --title "Comidas" {span} '
                        "--amount <por persona y día> --per-day --per-person"),
        })
    if not has_misc:
        questions.append({
            "key": "misc",
            "text": ("No hay gastos varios (transporte local, propinas, "
                     "souvenirs, imprevistos). ¿Cuánto reserváis al día?" if es else
                     "No misc expenses yet (local transport, tips, souvenirs, "
                     "contingency). How much per day do you set aside?"),
            "command": (f'add --type other --title "Varios" {span} '
                        "--amount <por día> --per-day"),
        })
    return {
        "nights_total": nights_total, "nights_covered": len(covered),
        "nights_missing": missing, "nights_gaps": gaps,
        "lodging_ok": bool(nights_total) and not missing,
        "has_food": has_food, "has_misc": has_misc,
        "daily_food_estimate": daily_food, "daily_misc_estimate": daily_misc,
        "ready": not missing and has_food and has_misc,
        "questions": questions,
    }


# --------------------------------------------------------------------------- #
# Bundle (the --json contract; renderers consume this)
# --------------------------------------------------------------------------- #
def sort_key(item):
    return (item.get("start") or "9999-12-31", item.get("end") or "",
            TYPES.index(item["type"]) if item.get("type") in TYPES else 99,
            int(item.get("id") or 0))


def item_notes(item, lang):
    """The item's own notes, prefixed with the pending tag (no flight direction)."""
    notes = sanitize_text(item.get("notes") or "")
    if item.get("status") == "pending":
        tag = LABELS[lang]["pending"]
        notes = f"{tag}{' · ' + notes if notes else ''}"
    return notes


def _flight_leg(it, lang, *, leg, day, origin, destination):
    """One leg of a return flight, as a stand-alone itinerary row.

    The money stays on the original item (a return flight is one purchase, so
    the budget table keeps a single line) — only the itinerary splits in two.
    """
    d = date.fromisoformat(day)
    label = LABELS[lang]["leg_out" if leg == "outbound" else "leg_back"]
    place = flight_place(origin, destination, False)
    display = dict(it["display"])
    display.update({
        "dates": fmt_span(d, d, lang),
        "place": sanitize_text(place),
        "activity": f'{it["display"]["activity"]} ({label})',
        "concept": f'{it["display"]["concept"]} ({label})',
        "notes": item_notes(it, lang),
    })
    return {**it, "start": day, "end": day, "place": place,
            "leg": leg, "display": display}


def build_itinerary(out_items, lang):
    """Itinerary rows: like the items, but each leg of a return flight is its own
    row, placed on its own date (outbound on --start, return on --end)."""
    rows = []
    for it in out_items:
        if (it.get("type") == "flight" and it.get("roundtrip")
                and it.get("origin") and it.get("destination")
                and it.get("start") and it.get("end")
                and it["end"] > it["start"]):
            rows.append(_flight_leg(it, lang, leg="outbound", day=it["start"],
                                    origin=it["origin"],
                                    destination=it["destination"]))
            rows.append(_flight_leg(it, lang, leg="return", day=it["end"],
                                    origin=it["destination"],
                                    destination=it["origin"]))
        else:
            rows.append(it)
    rows.sort(key=lambda r: sort_key(r) + (1 if r.get("leg") == "return" else 0,))
    return rows


def build_bundle(doc, lang=None, emoji=True, today=None):
    lang = lang or doc.get("lang") or "es"
    if lang not in LABELS:
        raise TripError("--lang must be es or en")
    cur = doc["currency"]
    items = sorted(doc["items"], key=sort_key)
    out_items, by_type = [], {}
    for it in items:
        start = date.fromisoformat(it["start"]) if it.get("start") else None
        end = date.fromisoformat(it["end"]) if it.get("end") else None
        badge = TYPE_EMOJI.get(it.get("type"), "") if emoji else ""
        title = sanitize_text(it.get("title") or "")
        qty = int(it.get("qty") or 1)
        concept = f"{badge} {title}".strip() + (f" x{qty}" if qty > 1 else "")
        activity = f"{badge} {title}".strip() + (f" (x{qty})" if qty > 1 else "")
        notes = item_notes(it, lang)
        if it.get("type") == "flight" and it.get("roundtrip") is not None:
            trip_kind = ("ida y vuelta" if lang == "es" else "round trip") \
                if it["roundtrip"] else ("solo ida" if lang == "es" else "one way")
            notes = f"{trip_kind}{' · ' + notes if notes else ''}"
        rate_note = ""
        if it.get("converted") is not None and it.get("currency") \
                and it["currency"] != cur and it.get("rate"):
            rate_note = fmt_rate(it["rate"], it["currency"], cur, lang)
        out_items.append({
            **it,
            "display": {
                "dates": fmt_span(start, end, lang),
                "concept": concept,
                "activity": activity,
                "place": sanitize_text(it.get("place") or ""),
                "notes": notes,
                "budget_notes": " · ".join(x for x in (notes, rate_note) if x),
                "amount": fmt_money(it["converted"], cur, lang)
                if it.get("converted") is not None else "—",
                "original": fmt_money(it["total"], it["currency"], lang)
                if it.get("total") is not None and it.get("currency") != cur
                else "—",
                "rate": rate_note,
                # http(s) only, even if the stored file was hand-edited
                "link": _clean_link_soft(it.get("link")),
            },
        })
        by_type[it.get("type", "other")] = round(
            by_type.get(it.get("type", "other"), 0) + (it.get("converted") or 0), 2)

    spent = round(sum(i.get("converted") or 0 for i in items), 2)
    budget = doc.get("budget")
    travelers = int(doc.get("travelers") or 1)
    days = trip_days(doc)
    totals = {
        "spent": spent, "budget": budget,
        "remaining": round(budget - spent, 2) if budget else None,
        "pct": round(100 * spent / budget) if budget else None,
        "per_person": round(spent / travelers, 2) if travelers else None,
        "per_day": round(spent / days, 2) if days else None,
        "by_type": by_type,
        "display": {
            "spent": fmt_money(spent, cur, lang),
            "budget": fmt_money(budget, cur, lang) if budget else None,
            "remaining": fmt_money(budget - spent, cur, lang) if budget else None,
            "per_person": fmt_money(spent / travelers, cur, lang) if travelers else None,
            "per_day": fmt_money(spent / days, cur, lang) if days else None,
            "by_type": {k: fmt_money(v, cur, lang) for k, v in by_type.items()},
        },
    }
    totals["breakdown"] = build_breakdown(items, cur, lang, days, travelers, spent)
    totals["display"]["avg_per_person_day"] = (
        fmt_money(spent / travelers / days, cur, lang) if travelers and days else "—")
    return {
        "schema": SCHEMA,
        "trip": {k: doc.get(k) for k in (
            "slug", "name", "destination", "start", "end", "travelers",
            "budget", "currency", "lang", "created", "updated")},
        "labels": LABELS[lang],
        "lang": lang,
        "items": out_items,
        "itinerary": build_itinerary(out_items, lang),
        "totals": totals,
        "checks": build_checks(doc, lang),
        "warnings": build_warnings(doc, lang, today),
        "generated": (today or date.today()).isoformat(),
    }


# --------------------------------------------------------------------------- #
# Text rendering
# --------------------------------------------------------------------------- #
def _table(headers, rows, aligns=None):
    if not rows:
        return ""
    aligns = aligns or ["l"] * len(headers)
    widths = [dwidth(h) for h in headers]
    for row in rows:
        for i, cell in enumerate(row):
            widths[i] = max(widths[i], dwidth(cell))

    def line(cells):
        parts = []
        for i, cell in enumerate(cells):
            parts.append(drjust(cell, widths[i]) if aligns[i] == "r"
                         else dljust(cell, widths[i]))
        return "  ".join(parts).rstrip()

    out = [line(headers), "-" * (sum(widths) + 2 * (len(widths) - 1))]
    out += [line(r) for r in rows]
    return "\n".join(out)


def render_itinerary_text(bundle, notes_width=44, with_warnings=True):
    L, lang = bundle["labels"], bundle["lang"]
    rows = []
    for it in bundle.get("itinerary") or bundle["items"]:
        d = it["display"]
        rows.append([d["dates"], dtrunc(d["place"], 24), dtrunc(d["activity"], 40),
                     dtrunc(d["notes"], notes_width), d["link"]])
    head = [L["date"], L["place"], L["activity"], L["notes"], L["link"]]
    body = _table(head, rows) or L["empty"]
    out = [L["itinerary"], "", body]
    if with_warnings and bundle["warnings"]:
        out.append("")
        out += ["⚠ " + sanitize_text(w) for w in bundle["warnings"]]
    return "\n".join(out)


def render_budget_text(bundle):
    L, t = bundle["labels"], bundle["totals"]
    cur = bundle["trip"]["currency"]
    rows = []
    for it in bundle["items"]:
        d = it["display"]
        rows.append([dtrunc(d["concept"], 40), d["dates"], d["amount"],
                     d["original"], dtrunc(d["budget_notes"], 48)])
    head = [L["concept"], L["dates"], f'{L["amount"]} {cur}', L["original"], L["notes"]]
    body = _table(head, rows, aligns=["l", "l", "r", "r", "l"]) or L["empty"]
    out = [f'\U0001F4B0 {L["budget"]}', "", body, ""]
    line = f'{L["total"]}: {t["display"]["spent"]}'
    if t["budget"]:
        line += (f' · {L["budget_line"]} {t["display"]["budget"]}'
                 f' · {L["remaining"]} {t["display"]["remaining"]}'
                 f' ({t["pct"]}%)')
    out.append(line)
    out.append(f'{L["per_person"]} {t["display"]["per_person"]} · '
               f'{L["per_day"]} {t["display"]["per_day"]}')
    return "\n".join(out)


def render_header_text(bundle):
    L, tr = bundle["labels"], bundle["trip"]
    lang = bundle["lang"]
    span = ""
    if tr.get("start"):
        span = fmt_span(date.fromisoformat(tr["start"]),
                        date.fromisoformat(tr["end"]) if tr.get("end") else None, lang)
    bits = [f'{L["trip"]}: {sanitize_text(tr.get("name") or tr["slug"])}']
    if tr.get("destination"):
        bits.append(sanitize_text(tr["destination"]))
    if span:
        bits.append(f'{span} ({trip_days(tr)} {L["days"]})')
    bits.append(f'{tr.get("travelers") or 1} {L["travelers"].lower()}')
    return " · ".join(bits)


def render_summary_text(bundle):
    """The end-of-planning report: overview, category breakdown, open questions."""
    L, t, tr = bundle["labels"], bundle["totals"], bundle["trip"]
    c, lang, cur = bundle["checks"], bundle["lang"], bundle["trip"]["currency"]
    es = lang == "es"
    out = [L["summary"], "", render_header_text(bundle)]
    line = f'{L["spent"]}: {t["display"]["spent"]}'
    if t.get("budget"):
        line += (f' · {L["budget_line"]}: {t["display"]["budget"]}'
                 f' · {L["remaining"]}: {t["display"]["remaining"]} ({t["pct"]}%)')
    out += [line, "", render_itinerary_text(bundle, with_warnings=False), "",
            L["breakdown"], ""]

    rows = [[f'{r["emoji"]} {r["label"]}', r["display"]["amount"],
             f'{r["pct"]:.1f}%'.replace(".", ",") if es else f'{r["pct"]:.1f}%',
             r["display"]["per_day"], r["display"]["per_person"]]
            for r in t["breakdown"]]
    if rows:
        rows.append([L["total_all"], t["display"]["spent"],
                     "100,0%" if es else "100.0%",
                     t["display"]["per_day"], t["display"]["per_person"]])
    out.append(_table(
        [L["category"], f'{L["amount"]} {cur}', L["share"], L["per_day_col"],
         L["per_person_col"]],
        rows, aligns=["l", "r", "r", "r", "r"]) or L["empty"])
    out += ["", f'{L["avg_per_day"]}: {t["display"]["per_day"]} · '
                f'{L["avg_per_person_day"]}: {t["display"]["avg_per_person_day"]}']

    out += ["", L["checks"], ""]
    if c["nights_total"]:
        if c["lodging_ok"]:
            out.append(f'  ✓ {"Alojamiento" if es else "Lodging"}: '
                       + (f'todas las noches cubiertas ({c["nights_covered"]}/'
                          f'{c["nights_total"]})' if es else
                          f'every night covered ({c["nights_covered"]}/'
                          f'{c["nights_total"]})'))
        else:
            out.append(f'  ✗ {"Alojamiento" if es else "Lodging"}: '
                       + (f'faltan {c["nights_missing"]} de {c["nights_total"]} '
                          f'noches ({c["nights_gaps"]})' if es else
                          f'{c["nights_missing"]} of {c["nights_total"]} nights '
                          f'missing ({c["nights_gaps"]})'))
    def state(present, daily):
        if not present:
            return "sin estimación" if es else "no estimate"
        if daily:
            return "estimación diaria incluida" if es else "daily estimate included"
        return "incluido (sin estimación diaria)" if es else \
            "present (no daily estimate)"

    for label_es, label_en, present, daily in (
            ("Comida", "Food", c["has_food"], c["daily_food_estimate"]),
            ("Varios", "Misc", c["has_misc"], c["daily_misc_estimate"])):
        out.append(f'  {"✓" if present else "✗"} '
                   f'{label_es if es else label_en}: {state(present, daily)}')

    if c["ready"]:
        out.append(f'  ✓ {L["ready"]}')
    if c["questions"]:
        out += ["", L["questions"], ""]
        for q in c["questions"]:
            out.append(f'  • {sanitize_text(q["text"])}')
            out.append(f'      → {q["command"]}')
    if bundle["warnings"]:
        out.append("")
        out += ["⚠ " + sanitize_text(w) for w in bundle["warnings"]]
    return "\n".join(out)


def render_text(bundle, what="both"):
    if what == "summary":
        return render_summary_text(bundle)
    parts = [render_header_text(bundle), ""]
    if what in ("both", "itinerary"):
        parts.append(render_itinerary_text(bundle))
    if what == "both":
        parts.append("")
    if what in ("both", "budget"):
        parts.append(render_budget_text(bundle))
    return "\n".join(parts)


# --------------------------------------------------------------------------- #
# Output helpers
# --------------------------------------------------------------------------- #
def safe_out_path(path, overwrite=False):
    p = os.path.abspath(os.path.expanduser(path))
    parent = os.path.realpath(os.path.dirname(p) or ".")
    if not os.path.isdir(parent):
        raise TripError(f"folder does not exist: {os.path.dirname(p)}")
    final = os.path.join(parent, os.path.basename(p))
    if os.path.lexists(final):
        if not overwrite:
            raise TripError(f"{final} already exists — pass --overwrite to replace it")
        if os.path.islink(final):
            raise TripError(f"refusing to write through a symlink: {final}")
    return final


def emit(text, path=None, overwrite=False, label="file"):
    if not path:
        print(text)
        return
    dest = safe_out_path(path, overwrite)
    atomic_write(dest, text if text.endswith("\n") else text + "\n", backup=False)
    print(f"OK — wrote {label}: {dest}")


def print_tables(base, doc, args, what="both", hint=True):
    if getattr(args, "quiet", False):
        return
    bundle = build_bundle(doc, lang=getattr(args, "lang", None),
                          emoji=not getattr(args, "no_emoji", False))
    print(render_text(bundle, what))
    if hint:
        # Every mutating command ends by handing the turn back to the user, so
        # the agent knows to wait and then run `summary`.
        print("\n▶ " + bundle["labels"]["done_hint"])


# --------------------------------------------------------------------------- #
# Subcommands
# --------------------------------------------------------------------------- #
def do_check(args):
    base = resolve_dir(args.dir)
    trips = list_trips(base)
    active = get_active(base)
    print(f"OK — trips folder: {base}")
    print(f"{len(trips)} trip(s); active: {active or '(none)'}")
    cache = read_rate_cache(base)
    if cache:
        age_h = (time.time() - float(cache.get("fetched_at") or 0)) / 3600
        print(f"FX cache: {len(cache['rates'])} currencies, "
              f"{age_h:.1f}h old, source(s): {', '.join(cache.get('sources') or ['?'])}"
              f", fetched via {cache.get('transport') or '?'}")
    else:
        print("FX cache: empty (rates are fetched on first conversion)")
    if not getattr(args, "offline", False):
        for name, url, parser in SOURCES:
            try:
                rates, _ = parser(http_get(url, timeout=8))
                print(f"  {name}: OK ({len(rates)} currencies)")
            except Exception as e:  # network probe must never fail `check`
                print(f"  {name}: unreachable ({str(e)[:60]})")
    return 0


def do_new(args):
    base = resolve_dir(args.dir)
    missing = [f"--{f}" for f in ("name", "destination", "start", "end")
               if not getattr(args, f, None)]
    if getattr(args, "travelers", None) is None:
        missing.append("--travelers")
    if missing:
        raise TripError(
            "missing " + ", ".join(missing) + " — ask the user for: destination, "
            "dates (start/end), how many travelers, and optionally the budget and "
            "preferred currency (default EUR).")
    lang = (args.lang or "es").lower()
    if lang not in LABELS:
        raise TripError("--lang must be es or en")
    start = parse_date(args.start)
    end = parse_date(args.end, start)
    if end < start:
        raise TripError("--end is before --start")
    slug = slugify(args.slug or f"{args.name}-{start.strftime('%Y-%m')}")
    path = trip_path(base, slug)
    if os.path.exists(path) and not args.force:
        raise TripError(f"trip {slug!r} already exists — use `use {slug}`, "
                        "pick another --slug, or pass --force to replace it")
    currency = (args.currency or "EUR").upper()
    if not re.fullmatch(r"[A-Z]{3}", currency):
        raise TripError("--currency must be a 3-letter code, e.g. EUR, USD, COP")
    budget = None
    if args.budget is not None:
        value, cur = parse_amount(args.budget, currency)
        budget = q2(value)
    doc = {
        "schema": SCHEMA, "slug": slug,
        "name": sanitize_text(args.name).strip(),
        "destination": sanitize_text(args.destination).strip(),
        "start": start.isoformat(), "end": end.isoformat(),
        "travelers": int(args.travelers), "budget": budget,
        "currency": currency, "lang": lang,
        "created": date.today().isoformat(), "items": [], "next_id": 1,
    }
    write_trip(base, doc)
    set_active(base, slug)
    print(f"OK — created trip {slug!r} (now active).")
    print_tables(base, doc, args)
    return 0


def do_list(args):
    base = resolve_dir(args.dir)
    trips = list_trips(base)
    active = get_active(base)
    if args.json:
        print(json.dumps({"active": active, "trips": [
            {"slug": t["slug"], "name": t.get("name"),
             "destination": t.get("destination"), "start": t.get("start"),
             "end": t.get("end"), "items": len(t["items"]),
             "currency": t["currency"],
             "spent": round(sum(i.get("converted") or 0 for i in t["items"]), 2),
             "budget": t.get("budget")} for t in trips]},
            indent=2, ensure_ascii=False))
        return 0
    if not trips:
        print("No trips yet. Create one with `new`.")
        return 0
    rows = []
    for t in trips:
        spent = sum(i.get("converted") or 0 for i in t["items"])
        rows.append([
            ("* " if t["slug"] == active else "  ") + t["slug"],
            sanitize_text(t.get("destination") or ""),
            f'{t.get("start") or "?"} → {t.get("end") or "?"}',
            str(len(t["items"])),
            fmt_money(spent, t["currency"], t.get("lang", "es")),
            fmt_money(t["budget"], t["currency"], t.get("lang", "es"))
            if t.get("budget") else "—",
        ])
    print(_table(["Trip", "Destination", "Dates", "Items", "Spent", "Budget"], rows,
                 aligns=["l", "l", "l", "r", "r", "r"]))
    return 0


def do_use(args):
    base = resolve_dir(args.dir)
    doc = read_trip(base, args.slug)
    set_active(base, doc["slug"])
    print(f"OK — active trip: {doc['slug']}")
    return 0


def do_set(args):
    base = resolve_dir(args.dir)
    doc = resolve_trip(base, args.trip)
    changed = []
    for field in ("name", "destination"):
        if getattr(args, field, None):
            doc[field] = sanitize_text(getattr(args, field)).strip()
            changed.append(field)
    if args.start:
        doc["start"] = parse_date(args.start).isoformat()
        changed.append("start")
    if args.end:
        doc["end"] = parse_date(args.end, date.fromisoformat(doc["start"])).isoformat()
        changed.append("end")
    if doc.get("end") and doc["end"] < doc["start"]:
        raise TripError("end date is before start date")
    if args.travelers is not None:
        doc["travelers"] = int(args.travelers)
        changed.append("travelers")
    if args.budget is not None:
        value, _ = parse_amount(args.budget, doc["currency"])
        doc["budget"] = q2(value)
        changed.append("budget")
    if args.lang:
        if args.lang not in LABELS:
            raise TripError("--lang must be es or en")
        doc["lang"] = args.lang
        changed.append("lang")
    if args.currency:
        new_cur = args.currency.upper()
        if not re.fullmatch(r"[A-Z]{3}", new_cur):
            raise TripError("--currency must be a 3-letter code")
        if new_cur != doc["currency"]:
            old = doc["currency"]
            doc["currency"] = new_cur
            ctx = None
            needed = {i.get("currency") for i in doc["items"]
                      if i.get("amount") is not None and i.get("currency") != new_cur}
            if needed:
                ctx = load_rates(base, need=sorted(needed) + [new_cur])
            for item in doc["items"]:
                if item.get("amount") is not None:
                    recost(item, doc, base, rates_ctx=ctx)
            if (doc.get("budget") is not None and old != new_cur
                    and args.budget is None and args.per_person_budget is None):
                print(f"note: --budget is still {doc['budget']} and is now read as "
                      f"{new_cur}; pass --budget to restate it.", file=sys.stderr)
            changed.append("currency")
    if args.per_person_budget is not None:
        value, _ = parse_amount(args.per_person_budget, doc["currency"])
        doc["budget"] = q2(value * int(doc.get("travelers") or 1))
        changed.append("budget")
    if not changed:
        raise TripError("nothing to change — pass e.g. --budget, --currency, --end")
    write_trip(base, doc)
    print(f"OK — updated: {', '.join(changed)}")
    print_tables(base, doc, args)
    return 0


def do_add(args):
    base = resolve_dir(args.dir)
    doc = resolve_trip(base, args.trip)
    item = {"id": next_id(doc)}
    apply_item_fields(item, args, doc, base, creating=True)
    dup = is_duplicate(doc, item)
    if dup and not args.force:
        raise TripError(
            f"looks like a duplicate of item {dup['id']} ({dup['title']}) — pass "
            f"--force to add it anyway, or `edit {dup['id']}` to change that one")
    doc["items"].append(item)
    write_trip(base, doc)
    print(f"OK — added item {item['id']}: {sanitize_text(item['title'])}")
    print_tables(base, doc, args)
    return 0


def do_edit(args):
    base = resolve_dir(args.dir)
    doc = resolve_trip(base, args.trip)
    item = find_item(doc, args.id)
    apply_item_fields(item, args, doc, base, creating=False)
    write_trip(base, doc)
    print(f"OK — updated item {item['id']}: {sanitize_text(item['title'])}")
    print_tables(base, doc, args)
    return 0


def do_rm(args):
    base = resolve_dir(args.dir)
    doc = resolve_trip(base, args.trip)
    item = find_item(doc, args.id)
    doc["items"] = [i for i in doc["items"] if i is not item]
    write_trip(base, doc)
    print(f"OK — removed item {item['id']}: {sanitize_text(item['title'])}")
    print_tables(base, doc, args)
    return 0


def do_undo(args):
    base = resolve_dir(args.dir)
    doc = resolve_trip(base, args.trip)
    path = trip_path(base, doc["slug"])
    bak = path + ".bak"
    if not os.path.exists(bak):
        raise TripError("nothing to undo (no backup for this trip yet)")
    with open(bak, "r", encoding="utf-8") as fh:
        prev = fh.read()
    atomic_write(path, prev)  # the current version becomes the new .bak (redo)
    print("OK — restored the previous version of the trip.")
    print_tables(base, read_trip(base, doc["slug"]), args)
    return 0


def do_show(args, what="both"):
    base = resolve_dir(args.dir)
    doc = resolve_trip(base, args.trip)
    bundle = build_bundle(doc, lang=args.lang, emoji=not args.no_emoji)
    if args.json:
        print(json.dumps(bundle, indent=2, ensure_ascii=False, sort_keys=True))
        return 0
    import render_trip  # local import: only needed for the export formats
    if args.html:
        emit(render_trip.render_html(bundle), args.out, args.overwrite, "HTML")
        return 0
    if args.ics:
        emit(render_trip.render_ics(bundle), args.out, args.overwrite, "calendar")
        return 0
    if args.markdown:
        emit(render_trip.render_markdown(bundle, what), args.out, args.overwrite,
             "Markdown")
        return 0
    print(render_text(bundle, what))
    return 0


def do_convert(args):
    base = resolve_dir(args.dir)
    doc = None
    try:
        doc = resolve_trip(base, args.trip)
    except TripError:
        pass
    default_to = (args.to or (doc or {}).get("currency") or "EUR").upper()
    value, cur = parse_amount(args.amount, args.currency)
    if not cur:
        raise TripError("say which currency: --amount '420 USD' or --currency USD")
    lang = args.lang or (doc or {}).get("lang") or "es"
    if cur == default_to:
        rate, source, day = 1.0, "same-currency", date.today().isoformat()
    else:
        ctx = load_rates(base, need=[cur, default_to], refresh=args.refresh)
        rate = cross_rate(ctx["rates"], cur, default_to)
        source = "+".join(ctx.get("sources") or []) or "cache"
        day = ctx.get("date") or date.today().isoformat()
        if ctx.get("stale"):
            source += " (cached)"
    converted = q2(Decimal(str(value)) * Decimal(str(rate)))
    if args.json:
        print(json.dumps({"amount": float(value), "from": cur, "to": default_to,
                          "rate": rate, "converted": converted,
                          "rate_date": day, "rate_source": source},
                         indent=2, sort_keys=True))
        return 0
    print(f"{fmt_money(value, cur, lang)} = {fmt_money(converted, default_to, lang)}"
          f"   ({fmt_rate(rate, cur, default_to, lang)}, {source} {day})")
    return 0


def do_rates(args):
    base = resolve_dir(args.dir)
    ctx = load_rates(base, need=args.currency, refresh=args.refresh)
    if args.json:
        print(json.dumps(ctx, indent=2, sort_keys=True))
        return 0
    age_h = (time.time() - float(ctx.get("fetched_at") or 0)) / 3600
    print(f"{len(ctx['rates'])} currencies, base EUR, date {ctx.get('date')}, "
          f"{age_h:.1f}h old, source(s): {', '.join(ctx.get('sources') or ['cache'])}"
          f", fetched via {ctx.get('transport') or 'cache'}"
          + ("  [STALE — served from cache]" if ctx.get("stale") else ""))
    show = [c for c in (args.currency, "USD", "GBP", "COP", "MXN")
            if c and c in ctx["rates"]]
    for code in dict.fromkeys(show):
        print(f"  1 EUR = {ctx['rates'][code]:,.4f} {code}")
    return 0


def do_maps(args):
    """Verification links only — this tool never computes distances itself."""
    a = urllib.parse.quote(sanitize_text(args.origin))
    b = urllib.parse.quote(sanitize_text(args.destination))
    links = {
        "driving": f"https://www.google.com/maps/dir/?api=1&origin={a}"
                   f"&destination={b}&travelmode=driving",
        "transit": f"https://www.google.com/maps/dir/?api=1&origin={a}"
                   f"&destination={b}&travelmode=transit",
        "flights": f"https://www.google.com/travel/flights?q="
                   f"{urllib.parse.quote('flights from ')}{a}"
                   f"{urllib.parse.quote(' to ')}{b}",
    }
    note = ("Distances/durations are NOT computed by this tool. If the agent "
            "states one, it is a model estimate that can be wrong — always show "
            "it as an estimate and give these links so the user can verify.")
    if args.json:
        print(json.dumps({"origin": args.origin, "destination": args.destination,
                          "links": links, "disclaimer": note},
                         indent=2, ensure_ascii=False))
        return 0
    print(note)
    for k, v in links.items():
        print(f"  {k}: {v}")
    return 0


# --------------------------------------------------------------------------- #
# CLI
# --------------------------------------------------------------------------- #
def add_item_flags(p):
    p.add_argument("--type", choices=TYPES, help="what kind of item this is")
    p.add_argument("--title", help="short name, e.g. 'Vuelo ida'")
    p.add_argument("--place", help="city/place shown in the itinerary")
    p.add_argument("--from", dest="origin", help="flight origin (city or airport)")
    p.add_argument("--to", dest="destination", help="flight destination")
    direction = p.add_mutually_exclusive_group()
    direction.add_argument("--roundtrip", action="store_true",
                           help="return flight (ida y vuelta)")
    direction.add_argument("--one-way", dest="one_way", action="store_true",
                           help="one-way flight (solo ida)")
    p.add_argument("--date", help="date or range: '13 ago', '13-16 ago', 2026-08-13")
    p.add_argument("--start", help="start date (with --end)")
    p.add_argument("--end", help="end date")
    p.add_argument("--amount", help="cost, e.g. 630, '420 USD', '2.450.000 COP'")
    p.add_argument("--currency", help="currency of --amount (default: trip currency)")
    p.add_argument("--rate", type=float,
                   help="manual exchange rate (1 unit of --currency in trip currency)")
    p.add_argument("--qty", type=int, help="multiplier, e.g. 2 flights (default 1)")
    p.add_argument("--per-person", action="store_true",
                   help="the amount is per traveler (multiplied by --travelers)")
    p.add_argument("--per-day", dest="per_day", action="store_true",
                   help="the amount is per day (multiplied by the item's days)")
    p.add_argument("--status", choices=["confirmed", "pending"],
                   help="pending = 'por confirmar'")
    p.add_argument("--link", help="booking/reference URL (http/https)")
    p.add_argument("--notes", help="short note")
    p.add_argument("--notes-file", help="read the note from a file (safer for long text)")
    p.add_argument("--force", action="store_true", help="skip the duplicate check")


def add_render_flags(p):
    p.add_argument("--json", action="store_true", help="machine-readable bundle")
    p.add_argument("--markdown", action="store_true", help="Markdown tables")
    p.add_argument("--html", action="store_true", help="one-file HTML page")
    p.add_argument("--ics", action="store_true", help="iCalendar events")
    p.add_argument("-o", "--out", help="write the output to this file")
    p.add_argument("--overwrite", action="store_true", help="replace an existing file")
    p.add_argument("--no-emoji", action="store_true", help="plain text, no emoji")
    p.add_argument("--lang", choices=["es", "en"], help="override the trip language")


def build_parser():
    p = argparse.ArgumentParser(
        prog="trip_planner",
        description="Plan a trip: itinerary + running budget with currency conversion.")
    p.add_argument("--dir", help="trips folder (default ~/.hermes/trips)")
    p.add_argument("--trip", help="trip id to act on (default: the active trip)")
    sub = p.add_subparsers(dest="cmd")

    c = sub.add_parser("check", help="verify the state folder + FX sources")
    c.add_argument("--offline", action="store_true", help="skip the network probe")

    n = sub.add_parser("new", help="create a trip")
    n.add_argument("--name", help="short trip name, e.g. 'Norte'")
    n.add_argument("--destination", help="where you are going")
    n.add_argument("--start", help="first day (YYYY-MM-DD or '13 ago')")
    n.add_argument("--end", help="last day")
    n.add_argument("--travelers", type=int, help="how many people travel")
    n.add_argument("--budget", help="total budget (optional)")
    n.add_argument("--currency", help="preferred currency (default EUR)")
    n.add_argument("--lang", choices=["es", "en"], help="table language (default es)")
    n.add_argument("--slug", help="explicit trip id")
    n.add_argument("--force", action="store_true", help="overwrite an existing trip")
    n.add_argument("--quiet", action="store_true", help="do not print the tables")
    n.add_argument("--no-emoji", action="store_true")

    ls = sub.add_parser("list", help="list trips")
    ls.add_argument("--json", action="store_true")

    u = sub.add_parser("use", help="set the active trip")
    u.add_argument("slug")

    s = sub.add_parser("set", help="change trip fields")
    s.add_argument("--name")
    s.add_argument("--destination")
    s.add_argument("--start")
    s.add_argument("--end")
    s.add_argument("--travelers", type=int)
    s.add_argument("--budget")
    s.add_argument("--per-person-budget", help="budget per traveler (× travelers)")
    s.add_argument("--currency", help="re-base every item into this currency")
    s.add_argument("--lang", choices=["es", "en"])
    s.add_argument("--quiet", action="store_true")
    s.add_argument("--no-emoji", action="store_true")

    a = sub.add_parser("add", help="add an item and print the updated tables")
    add_item_flags(a)
    a.add_argument("--quiet", action="store_true")
    a.add_argument("--no-emoji", action="store_true")
    a.add_argument("--lang", choices=["es", "en"])

    e = sub.add_parser("edit", help="change an item")
    e.add_argument("id")
    add_item_flags(e)
    e.add_argument("--quiet", action="store_true")
    e.add_argument("--no-emoji", action="store_true")
    e.add_argument("--lang", choices=["es", "en"])

    r = sub.add_parser("rm", help="remove an item")
    r.add_argument("id")
    r.add_argument("--quiet", action="store_true")
    r.add_argument("--no-emoji", action="store_true")
    r.add_argument("--lang", choices=["es", "en"])

    ud = sub.add_parser("undo", help="restore the previous version of the trip")
    ud.add_argument("--quiet", action="store_true")
    ud.add_argument("--no-emoji", action="store_true")
    ud.add_argument("--lang", choices=["es", "en"])

    for name, help_text in (("show", "itinerary + budget"),
                            ("itinerary", "just the itinerary"),
                            ("budget", "just the budget"),
                            ("summary", "final report: breakdown + checks")):
        sp = sub.add_parser(name, help=help_text)
        add_render_flags(sp)

    cv = sub.add_parser("convert", help="convert an amount into the trip currency")
    cv.add_argument("--amount", required=True, help="e.g. '420 USD'")
    cv.add_argument("--currency", help="source currency if not in --amount")
    cv.add_argument("--to", help="target currency (default: trip currency)")
    cv.add_argument("--refresh", action="store_true", help="force a rate refresh")
    cv.add_argument("--json", action="store_true")
    cv.add_argument("--lang", choices=["es", "en"])

    rt = sub.add_parser("rates", help="show / refresh the FX cache")
    rt.add_argument("--currency", help="make sure this currency is present")
    rt.add_argument("--refresh", action="store_true")
    rt.add_argument("--json", action="store_true")

    mp = sub.add_parser("maps", help="Google Maps/Flights links (no network, no math)")
    mp.add_argument("--from", dest="origin", required=True)
    mp.add_argument("--to", dest="destination", required=True)
    mp.add_argument("--json", action="store_true")
    return p


DISPATCH = {
    "check": do_check, "new": do_new, "list": do_list, "use": do_use,
    "set": do_set, "add": do_add, "edit": do_edit, "rm": do_rm, "undo": do_undo,
    "convert": do_convert, "rates": do_rates, "maps": do_maps,
}


def main(argv=None):
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    args = build_parser().parse_args(argv)
    try:
        if args.cmd in DISPATCH:
            return DISPATCH[args.cmd](args)
        if args.cmd in ("show", None):
            if args.cmd is None:
                raise TripError(
                    "say what to do: check | new | add | show | list — see SKILL.md")
            return do_show(args, "both")
        if args.cmd == "itinerary":
            return do_show(args, "itinerary")
        if args.cmd == "budget":
            return do_show(args, "budget")
        if args.cmd == "summary":
            return do_show(args, "summary")
        raise TripError(f"unknown command {args.cmd!r}")
    except TripError as e:
        print(f"error: {e}", file=sys.stderr)
        return 1
    except BrokenPipeError:
        return 0
    except KeyboardInterrupt:
        return 130


if __name__ == "__main__":
    sys.exit(main())
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall