#!/usr/bin/env python3
"""clock — the agent's authoritative time/date source.

Why this exists: an LLM's sense of "now" is frozen at training time, and its
date arithmetic is a documented error source (day-of-week, UTC-vs-local day
rollover, DST, "3 hours ago", ISO week boundaries). Every date/time claim the
agent makes about an event should be DERIVED — from a log line, a file mtime,
or this tool — never guessed.

Usage:
  clock                          full report for now (UTC + local + epoch + week + NTP)
  clock --line                   one compact line (what the agent loop injects)
  clock --json                   machine-readable snapshot
  clock --sync                   NTP/RTC sync detail (skew, last sync, source)

  clock <WHEN> ...               normalise/convert: epoch, ISO-8601, syslog
                                 'Oct 24 20:59:47', 'yesterday', '2h ago', 'in 3d',
                                 '-90m', '2026-10-25', '2026-10-25 01:59:47 UTC'
  clock --since <WHEN>           how long ago an event was, broken down
  clock --until <WHEN>           how long until something
  clock --add 90m [--from WHEN]  time arithmetic (also --sub)
  clock --tz America/New_York    render in another zone as well

Exit: 0 ok, 2 unparseable time, 3 arithmetic/zone error.

Conventions worth remembering (they cause real misreadings on this host):
  * memory.md / audit.jsonl / last_run.log timestamps are UTC ("...Z").
  * journalctl, `ls -l`, `date` show LOCAL time (America/Chicago).
  * In the evening, the local calendar date is often ONE DAY BEHIND UTC.
    `clock --line` warns when that is the case — quote the zone when it matters.
"""

from __future__ import annotations

import argparse
import datetime as dt
import json
import os
import re
import sys
from pathlib import Path

try:
    from zoneinfo import ZoneInfo
except ImportError:  # pragma: no cover - python < 3.9
    ZoneInfo = None  # type: ignore[assignment]

UTC = dt.timezone.utc
SYNC_FLAG = Path("/run/systemd/timesync/synchronized")

UNITS = {
    "s": 1, "sec": 1, "secs": 1, "second": 1, "seconds": 1,
    "m": 60, "min": 60, "mins": 60, "minute": 60, "minutes": 60,
    "h": 3600, "hr": 3600, "hrs": 3600, "hour": 3600, "hours": 3600,
    "d": 86400, "day": 86400, "days": 86400,
    "w": 604800, "wk": 604800, "week": 604800, "weeks": 604800,
}


# ── formatting helpers ──────────────────────────────────────────────────────
def now_local() -> dt.datetime:
    """Current time, local zone, tz-aware."""
    return dt.datetime.now().astimezone()


def iso_utc(t: dt.datetime) -> str:
    return t.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")


def zone_label(t: dt.datetime) -> str:
    ab = t.tzname() or "local"
    return f"{ab} ({fmt_offset(t.utcoffset())})"


def local_str(t: dt.datetime) -> str:
    """e.g. 'Sat 2026-10-24 20:59:47 CDT (-05:00)'."""
    loc = t.astimezone()
    return f"{loc.strftime('%a %Y-%m-%d %H:%M:%S')} {zone_label(loc)}"


def zone_name(t: dt.datetime) -> str:
    """IANA zone name where we can determine it, else the abbreviation.

    `datetime.now().astimezone()` yields a FIXED-OFFSET tzinfo (e.g. 'CDT', plus a
    'CST' str() quirk), so resolve the name from TZ or the /etc/localtime symlink.
    """
    key = getattr(t.astimezone(), "tzinfo", None)
    name = getattr(key, "key", None)  # zoneinfo keeps its key
    if name:
        return name
    env_tz = os.environ.get("TZ")
    if env_tz:
        return env_tz
    try:
        link = os.readlink("/etc/localtime")
        if "zoneinfo/" in link:
            return link.split("zoneinfo/", 1)[1]
    except OSError:
        pass
    return t.astimezone().tzname() or zone_label(t)


def fmt_offset(off: dt.timedelta | None) -> str:
    """'+05:30' / '-06:00' — str(timedelta) prints '-1 day, 20:00:00' for negatives."""
    mins = int((off or dt.timedelta(0)).total_seconds() // 60)
    sign = "+" if mins >= 0 else "-"
    mins = abs(mins)
    return f"{sign}{mins // 60:02d}:{mins % 60:02d}"


def span(seconds: float) -> str:
    """Compact duration: '2d 4h', '3h 12m', '45s' (max two units, floor)."""
    secs = abs(int(round(float(seconds))))
    if secs < 1:
        return "0s"
    parts: list[str] = []
    for name, size in (("d", 86400), ("h", 3600), ("m", 60), ("s", 1)):
        if secs >= size and len(parts) < 2:
            n, secs = divmod(secs, size)
            parts.append(f"{n}{name}")
    return " ".join(parts) if parts else "0s"


def ago(then: dt.datetime, now: dt.datetime | None = None) -> str:
    """'3h 12m ago' / 'in 45m' / 'just now'."""
    now = now or now_local()
    delta = (now - then).total_seconds()
    if abs(delta) < 2:
        return "just now"
    return f"{span(delta)} ago" if delta > 0 else f"in {span(delta)}"


def sync_state() -> tuple[bool | None, str]:
    """(synchronised?, short text). /run flag first: it is instant and authoritative
    for systemd-timesyncd; fall back to chrony's socket/tracking if present."""
    if SYNC_FLAG.exists():
        try:
            raw = SYNC_FLAG.read_text(encoding="utf-8", errors="replace").strip()
        except OSError:
            raw = "1"
        return True, "synced (systemd-timesyncd)"
    chrony_sock = Path("/run/chrony/chronyd.sock")
    if chrony_sock.exists():
        return True, "chrony daemon running"
    return None, "UNSYNCHRONISED (no timesyncd sync flag, no chrony socket)"


def sync_detail() -> str:
    """Long form for --sync: timedatectl + timesync-status / chronyc tracking."""
    import subprocess

    out: list[str] = []
    for cmd in (
        ["timedatectl", "show", "-p", "Timezone", "-p", "NTPSynchronized",
         "-p", "NTP", "-p", "LocalRTC"],
        ["timedatectl", "timesync-status"],
    ):
        try:
            r = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
            body = (r.stdout or r.stderr or "").strip()
        except Exception as exc:  # noqa: BLE001
            body = f"<{type(exc).__name__}: {exc}>"
        if body:
            out.append("$ " + " ".join(cmd) + "\n" + body)
    try:
        r = subprocess.run(["chronyc", "tracking"], capture_output=True, text=True, timeout=10)
        if r.returncode == 0 and r.stdout.strip():
            out.append("$ chronyc tracking\n" + r.stdout.strip())
    except Exception:  # noqa: BLE001 - chrony is optional
        pass
    return "\n\n".join(out)


# ── parsing ─────────────────────────────────────────────────────────────────
def _localises(moment: dt.datetime) -> dt.datetime:
    """Interpret a naive datetime in the host's LOCAL zone."""
    return moment.astimezone()


def _abbrev_zones() -> dict[str, dt.tzinfo]:
    """Map the local zone's own abbreviations (e.g. CST/CDT) to tzinfo, so
    '2026-10-24 20:59:47 CDT' parses without a tz database guess."""
    now = now_local()
    zones: dict[str, dt.tzinfo] = {"UTC": UTC, "GMT": UTC, "Z": UTC, "UT": UTC}
    for m in range(1, 13):
        for day in (1, 15):
            probe = dt.datetime(now.year, m, day, 12, tzinfo=now.tzinfo)
            for ab in (probe.tzname(), now.replace(month=m, day=day).tzname()):
                if ab:
                    zones[ab.upper()] = probe.tzinfo or now.tzinfo
    if now.tzname():
        zones[now.tzname().upper()] = now.tzinfo
    return zones


_REL_RE = re.compile(r"^(?:(in)\s+)?([+-]?\d+(?:\.\d+)?)\s*([a-z]+)(?:\s+(ago))?$", re.I)

_DATE_FORMATS = (
    "%Y-%m-%dT%H:%M:%S",
    "%Y-%m-%dT%H:%M",
    "%Y-%m-%d %H:%M:%S",
    "%Y-%m-%d %H:%M",
    "%Y-%m-%d",
    "%Y/%m/%d %H:%M:%S",
    "%Y/%m/%d",
    "%d/%m/%Y %H:%M",
    "%m/%d/%Y %H:%M",
    "%a %b %d %H:%M:%S %Y",
    "%a %b %d %H:%M:%S",
    "%b %d %H:%M:%S %Y",
    "%b %d %H:%M:%S",       # journalctl --output=short, year-less
    "%b %d %Y %H:%M:%S",
)


def parse_when(text: str, *, now: dt.datetime | None = None) -> tuple[dt.datetime, str]:
    """Parse a flexible time expression -> (aware datetime, kind). Raises ValueError."""
    now = now or now_local()
    raw = str(text).strip()
    if not raw:
        raise ValueError("empty time value")
    s = raw.strip()
    low = s.lower()

    if low in {"now", "right now"}:
        return now, "now"
    if low in {"today", "start of today", "midnight"}:
        return now.replace(hour=0, minute=0, second=0, microsecond=0), "start of local day"
    if low == "yesterday":
        return (now - dt.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0), "start of local yesterday"
    if low == "tomorrow":
        return (now + dt.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0), "start of local tomorrow"

    # Unix epoch (seconds, or milliseconds when 13 digits)
    if re.fullmatch(r"\d{9,13}(?:\.\d+)?", s):
        val = float(s)
        if len(s.split(".")[0]) >= 13:
            val /= 1000.0
        return dt.datetime.fromtimestamp(val, UTC), "epoch"

    # Relative: '2h ago', 'in 3d', '-90m', '+2 weeks'
    m = _REL_RE.match(s)
    if m:
        unit = m.group(3).lower()
        if unit in UNITS:
            val = float(m.group(2)) * UNITS[unit]
            if m.group(4):          # "2h ago"
                val = -abs(val)
            elif m.group(1):        # "in 2h"
                val = abs(val)
            return now + dt.timedelta(seconds=val), "relative"

    # Trailing zone word ("... UTC", "... CDT", "... CST")
    zones = _abbrev_zones()
    tz: dt.tzinfo | None = None
    tail = s.split()[-1].upper()
    if tail in zones:
        tz = zones[tail]
        s = s[: -len(tail)].strip()

    # ISO-8601 (python 3.11+ handles 'Z' and space separator)
    try:
        parsed = dt.datetime.fromisoformat(s.replace("Z", "+00:00") if s.endswith("Z") else s)
        if parsed.tzinfo is None:
            parsed = parsed.replace(tzinfo=tz) if tz else _localises(parsed)
        return parsed, "iso" if tz is None else "iso+zone"
    except ValueError:
        pass

    for fmt in _DATE_FORMATS:
        try:
            parsed = dt.datetime.strptime(s, fmt)
        except ValueError:
            continue
        if "%Y" not in fmt:
            parsed = parsed.replace(year=now.year)
            probe = parsed.replace(tzinfo=tz) if tz else _localises(parsed)
            if probe > now + dt.timedelta(days=1):
                parsed = parsed.replace(year=now.year - 1)
        if tz is not None:
            return parsed.replace(tzinfo=tz), "format+zone"
        return _localises(parsed), "format"

    raise ValueError(
        f"cannot parse time {raw!r} — try epoch (1792893587), ISO "
        "(2026-10-25T01:59:47Z), 'YYYY-MM-DD HH:MM', syslog 'Oct 24 20:59:47', "
        "'yesterday', '2h ago' or 'in 3d'"
    )


# ── rendering ───────────────────────────────────────────────────────────────
def rollover_note(t: dt.datetime) -> str:
    """Warn when the local calendar date differs from the UTC date."""
    loc = t.astimezone()
    utc = t.astimezone(UTC)
    if loc.date() == utc.date():
        return ""
    days = (utc.date() - loc.date()).days
    if days == 1:
        return (f"local date {loc.date()} is 1 day BEHIND UTC date {utc.date()} "
                f"(evening in America/Chicago) — say which zone you mean")
    if days == -1:
        return (f"local date {loc.date()} is 1 day AHEAD of UTC date {utc.date()} "
                f"— say which zone you mean")
    return f"local date {loc.date()} differs from UTC date {utc.date()} by {days} days"


def line(t: dt.datetime | None = None) -> str:
    t = t or now_local()
    synced, synctext = sync_state()
    loc = t.astimezone()
    parts = [
        f"now: {iso_utc(t)} ({t.astimezone(UTC).strftime('%a')})",
        f"local: {local_str(t)} tz={zone_name(t)}",
        f"epoch: {int(t.timestamp())}",
        f"ISO-week: {t.astimezone(UTC).isocalendar()[0]}-W{t.astimezone(UTC).isocalendar()[1]:02d}",
        f"NTP: {synctext}{'' if synced else ' ⚠'}",
    ]
    out = " · ".join(parts)
    note = rollover_note(t)
    if note:
        out += f"\nnote: {note}"
    return out


def report(t: dt.datetime | None = None, extra_zones: list[str] | None = None) -> str:
    t = t or now_local()
    loc = t.astimezone()
    utc = t.astimezone(UTC)
    iso = utc.isocalendar()
    synced, synctext = sync_state()
    lines = [
        f"UTC          {iso_utc(t)}  ({utc.strftime('%A')})",
        f"local        {local_str(t)}  [{zone_name(t)}]",
        f"epoch        {int(t.timestamp())}   ({t.timestamp():.3f})",
        f"ISO week     {iso[0]}-W{iso[1]:02d}-{iso[2]}   day {utc.timetuple().tm_yday}/365",
        f"RFC 2822     {utc.strftime('%a, %d %b %Y %H:%M:%S +0000')}",
        f"NTP          {synctext}",
    ]
    if SYNC_FLAG.exists():
        try:
            st = SYNC_FLAG.stat()
            age = t.timestamp() - st.st_mtime
            lines.append(f"last sync    {dt.datetime.fromtimestamp(st.st_mtime, UTC).strftime('%Y-%m-%dT%H:%M:%SZ')} ({span(age)} ago)")
        except OSError:
            pass
    for zone in extra_zones or []:
        if ZoneInfo is None:
            lines.append(f"{zone}: zoneinfo unavailable in this python")
            break
        try:
            other = t.astimezone(ZoneInfo(zone))
        except Exception as exc:  # noqa: BLE001
            raise ValueError(f"unknown time zone {zone!r}: {exc}") from exc
        lines.append(
            f"{zone:<12} {other.strftime('%a %Y-%m-%d %H:%M:%S %Z')} "
            f"({fmt_offset(other.utcoffset())})"
        )
    note = rollover_note(t)
    if note:
        lines.append(f"⚠ {note}")
    return "\n".join(lines)


def describe(when: dt.datetime, now: dt.datetime, kind: str) -> str:
    return (
        f"{iso_utc(when)}  ({when.astimezone(UTC).strftime('%a')})  "
        f"| local {local_str(when)}  "
        f"| epoch {int(when.timestamp())}  "
        f"| {ago(when, now)}  [{kind}]"
    )


def snapshot(t: dt.datetime | None = None) -> dict:
    t = t or now_local()
    loc = t.astimezone()
    utc = t.astimezone(UTC)
    synced, synctext = sync_state()
    iso = utc.isocalendar()
    return {
        "utc": iso_utc(t),
        "utc_weekday": utc.strftime("%A"),
        "local": loc.strftime("%Y-%m-%d %H:%M:%S"),
        "local_weekday": loc.strftime("%A"),
        "local_tz": zone_name(t),
        "local_offset": zone_label(loc),
        "epoch": int(t.timestamp()),
        "iso_week": f"{iso[0]}-W{iso[1]:02d}-{iso[2]}",
        "day_of_year": utc.timetuple().tm_yday,
        "ntp_synced": synced,
        "ntp": synctext,
        "local_utc_date_rollover_days": (utc.date() - loc.date()).days,
    }


def main(argv: list[str]) -> int:
    # '-90m' reads as an option to argparse; it is really "90m ago". Rewrite those
    # before parsing so relative-with-minus works without a '--' separator.
    argv = [re.sub(r"^-(\d+(?:\.\d+)?[a-z]+)$", r"\1 ago", a) for a in argv]
    ap = argparse.ArgumentParser(
        prog="clock",
        description="Authoritative time/date source: now, conversions, durations, NTP sync.",
    )
    ap.add_argument("when", nargs="*", help="time expression(s) to normalise")
    ap.add_argument("--line", action="store_true", help="one compact line (prompt injection)")
    ap.add_argument("--json", action="store_true", help="machine-readable snapshot")
    ap.add_argument("--sync", action="store_true", help="NTP/RTC sync detail")
    ap.add_argument("--tz", action="append", default=[], metavar="ZONE",
                    help="also render in this IANA zone (repeatable)")
    ap.add_argument("--since", metavar="WHEN", help="how long ago WHEN was")
    ap.add_argument("--until", metavar="WHEN", help="how long until WHEN")
    ap.add_argument("--add", metavar="DURATION", help="add a duration to --from (default now), e.g. 90m, 2d, 1h30m")
    ap.add_argument("--sub", metavar="DURATION", help="subtract a duration from --from (default now)")
    ap.add_argument("--from", dest="from_", metavar="WHEN", help="reference time for --add/--sub")
    args = ap.parse_args(argv)

    now = now_local()

    try:
        if args.sync:
            print(line(now))
            print()
            print(sync_detail() or "(no sync detail available)")
            return 0

        if args.json:
            print(json.dumps(snapshot(now), indent=2))
            return 0

        if args.add or args.sub:
            expr = args.add or args.sub
            m = re.fullmatch(r"(?:\d+(?:\.\d+)?[a-z]+\s*)+", expr.strip().lower())
            if not m:
                print(f"clock: bad duration {expr!r} — use forms like 90m, 2h, 3d, 1h30m", file=sys.stderr)
                return 3
            total = 0.0
            for num, unit in re.findall(r"(\d+(?:\.\d+)?)\s*([a-z]+)", expr.lower()):
                if unit not in UNITS:
                    print(f"clock: unknown duration unit {unit!r}", file=sys.stderr)
                    return 3
                total += float(num) * UNITS[unit]
            base, kind = (parse_when(args.from_, now=now) if args.from_ else (now, "now"))
            signed = total if args.add else -total
            result = base + dt.timedelta(seconds=signed)
            sign = "+" if signed >= 0 else "-"
            print(describe(result, now, f"{kind} {sign}{args.add or args.sub}"))
            return 0

        if args.since or args.until:
            out: list[str] = []
            if args.since:
                t, kind = parse_when(args.since, now=now)
                out.append(f"since {iso_utc(t)} — {ago(t, now)}  (exact: {span((now - t).total_seconds())}) [{kind}]")
            if args.until:
                t, kind = parse_when(args.until, now=now)
                remaining = (t - now).total_seconds()
                word = ago(t, now)
                out.append(f"until {iso_utc(t)} — {word}  (exact: {span(remaining)}) [{kind}]")
            print("\n".join(out))
            return 0

        if args.when:
            for w in args.when:
                t, kind = parse_when(w, now=now)
                print(describe(t, now, kind))
            note = rollover_note(now)
            if note:
                print(f"\n⚠ {note}")
            return 0

        if args.line:
            print(line(now))
            return 0

        print(report(now, args.tz))
        return 0
    except ValueError as exc:
        print(f"clock: {exc}", file=sys.stderr)
        return 2


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
