#!/usr/bin/env python3
# tzconv - convert a time between time zones (built-in zone table, system tzdata when present)
# Usage: tzconv TIME FROM [TO] [--date YYYY-MM-DD] [--list]
#   TIME is HH:MM (24h). With no TO, shows the time in every known zone.
#   Uses zoneinfo + system tzdata when available (DST-correct), else a built-in
#   fixed-offset table. Example: tzconv 12:00 UTC America/New_York
import argparse, sys
from datetime import datetime, date, time, timedelta, timezone

# Built-in fallback table: zone -> standard UTC offset in hours (no DST).
# Used only when zoneinfo/tzdata is unavailable.
TABLE = {
    "UTC": 0, "GMT": 0, "EST": -5, "EDT": -4, "CST": -6, "CDT": -5,
    "MST": -7, "MDT": -6, "PST": -8, "PDT": -7,
    "America/New_York": -5, "America/Chicago": -6, "America/Denver": -7,
    "America/Los_Angeles": -8, "America/Anchorage": -9, "Pacific/Honolulu": -10,
    "America/Toronto": -5, "America/Mexico_City": -6, "America/Sao_Paulo": -3,
    "Europe/London": 0, "Europe/Paris": 1, "Europe/Berlin": 1,
    "Europe/Moscow": 3, "Africa/Cairo": 2, "Africa/Lagos": 1,
    "Asia/Dubai": 4, "Asia/Karachi": 5, "Asia/Kolkata": 5.5, "Asia/Dhaka": 6,
    "Asia/Bangkok": 7, "Asia/Shanghai": 8, "Asia/Tokyo": 9, "Asia/Seoul": 9,
    "Australia/Sydney": 10, "Australia/Perth": 8, "Pacific/Auckland": 12,
}
ALIASES = {"NY": "America/New_York", "LA": "America/Los_Angeles",
           "London": "Europe/London", "Paris": "Europe/Paris",
           "Tokyo": "Asia/Tokyo", "Sydney": "Australia/Sydney"}

def get_tz(name):
    name = ALIASES.get(name, name)
    try:
        from zoneinfo import ZoneInfo
        return ZoneInfo(name), True
    except Exception:
        if name in TABLE:
            return timezone(timedelta(hours=TABLE[name])), False
        raise ValueError(f"unknown zone {name!r} (try --list)")

def selftest():
    tz, ok = get_tz("UTC")
    assert datetime(2026, 1, 1, 12, tzinfo=tz).utcoffset() == timedelta(0)
    # Jan: New York is EST (-5) whether via tzdata or the fallback table
    ny, _ = get_tz("America/New_York")
    assert datetime(2026, 1, 1, 12, tzinfo=ny).utcoffset() == timedelta(hours=-5)
    utc = datetime(2026, 1, 1, 12, tzinfo=timezone.utc).astimezone(ny)
    assert (utc.hour, utc.minute) == (7, 0)
    print("tzconv selftest: ok (UTC offset, NY -5 in January, 12:00 UTC = 07:00 NY)")
    return 0

def main():
    p = argparse.ArgumentParser(prog="tzconv",
        description="Convert a time between time zones (zoneinfo when present, built-in table otherwise).")
    p.add_argument("time", nargs="?", help="time HH:MM (24h)")
    p.add_argument("from_zone", nargs="?", help="source zone, e.g. UTC or America/New_York")
    p.add_argument("to_zone", nargs="?", help="target zone (omit to show all zones)")
    p.add_argument("--date", help="date YYYY-MM-DD (default today; matters for DST)")
    p.add_argument("--list", action="store_true", help="list known zones and exit")
    p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
    a = p.parse_args()
    if a.selftest:
        return selftest()
    if a.list:
        for z in sorted(TABLE):
            print(z)
        return 0
    if not a.time or not a.from_zone:
        p.error("TIME and FROM zone are required (or use --list)")
    try:
        hh, mm = (int(x) for x in a.time.strip().split(":"))
        d = date.fromisoformat(a.date) if a.date else date.today()
        src_tz, src_ok = get_tz(a.from_zone)
    except ValueError as e:
        print(f"tzconv: {e}", file=sys.stderr); return 2
    try:
        src = datetime.combine(d, time(hh, mm), tzinfo=src_tz)
    except ValueError as e:
        print(f"tzconv: {e}", file=sys.stderr); return 2
    if a.to_zone:
        try:
            dst_tz, _ = get_tz(a.to_zone)
        except ValueError as e:
            print(f"tzconv: {e}", file=sys.stderr); return 2
        out = src.astimezone(dst_tz)
        print(f"{src.strftime('%Y-%m-%d %H:%M')} {a.from_zone} = "
              f"{out.strftime('%Y-%m-%d %H:%M')} {a.to_zone}")
    else:
        for z in sorted(TABLE):
            try:
                tz, _ = get_tz(z)
            except ValueError:
                continue
            out = src.astimezone(tz)
            print(f"  {z:<22} {out.strftime('%Y-%m-%d %H:%M')}")
    if not src_ok:
        print("(note: using built-in fixed offsets — install tzdata for DST-correct results)",
              file=sys.stderr)
    return 0

if __name__ == "__main__":
    sys.exit(main())
