#!/usr/bin/env python3
"""Convert UTC timestamps to Melbourne local time (AEST/AEDT).

Usage:
    ./utc-to-melb TIMESTAMP [TIMESTAMP ...]

    TIMESTAMP can be:
        - ISO 8601:  2026-05-04T23:32:51Z, 2026-05-04T23:32:51+00:00
        - Compact:   20260504_233251
        - Date only: 2026-05-04 (assumes 00:00:00 UTC)

Output:
    For each input, prints the Melbourne local time in ISO 8601 format with
    the timezone abbreviation appended (AEST or AEDT).

Examples:
    ./utc-to-melb 2026-05-04T23:32:51Z
    2026-05-05T09:32:51+10:00 AEST

    ./utc-to-melb 20260504_233251 2026-01-15T12:00:00Z
    2026-05-05T09:32:51+10:00 AEST
    2026-01-15T23:00:00+11:00 AEDT
"""
import sys
from datetime import datetime, timezone
from zoneinfo import ZoneInfo

MELBOURNE = ZoneInfo("Australia/Melbourne")


def parse_timestamp(ts: str) -> datetime:
    """Parse various UTC timestamp formats into a timezone-aware datetime."""
    ts = ts.strip()

    # Compact format: 20260504_233251
    if len(ts) == 15 and ts[8] == "_" and ts.replace("_", "").isdigit():
        dt = datetime.strptime(ts, "%Y%m%d_%H%M%S")
        return dt.replace(tzinfo=timezone.utc)

    # Date only: 2026-05-04
    if len(ts) == 10 and ts[4] == "-" and ts[7] == "-":
        dt = datetime.strptime(ts, "%Y-%m-%d")
        return dt.replace(tzinfo=timezone.utc)

    # ISO 8601 with Z suffix
    if ts.endswith("Z"):
        ts = ts[:-1] + "+00:00"

    dt = datetime.fromisoformat(ts)
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    return dt


def to_melbourne(dt: datetime) -> tuple[str, str]:
    """Convert a UTC datetime to Melbourne local time. Returns (iso_string, tz_abbrev)."""
    melb_dt = dt.astimezone(MELBOURNE)
    abbrev = "AEDT" if melb_dt.utcoffset().total_seconds() == 11 * 3600 else "AEST"
    return melb_dt.isoformat(), abbrev


def main():
    if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
        print(__doc__.strip())
        sys.exit(0)

    for ts_arg in sys.argv[1:]:
        try:
            dt = parse_timestamp(ts_arg)
            iso_str, abbrev = to_melbourne(dt)
            print(f"{iso_str} {abbrev}")
        except (ValueError, TypeError) as e:
            print(f"Error parsing '{ts_arg}': {e}", file=sys.stderr)
            sys.exit(1)


if __name__ == "__main__":
    main()
