"""Portable calendar and inherited-file-descriptor lock helpers for cron."""

from __future__ import annotations

import fcntl
import math
import sys
import time
from datetime import date, datetime, timedelta
from zoneinfo import ZoneInfo


def now() -> datetime:
    return datetime.now(ZoneInfo("Europe/Paris"))


def parse_date(value: str) -> date:
    result = date.fromisoformat(value)
    if result.isoformat() != value:
        raise ValueError("Invalid ISO date")
    return result


def main() -> int:
    command, *args = sys.argv[1:]
    try:
        if command == "dates":
            today = now().date()
            start = parse_date(args[0]) if args[0] else today - timedelta(days=6)
            end = parse_date(args[1]) if args[1] else today - timedelta(days=1)
            if start > end:
                raise ValueError("Invalid range")
            print(today, start, end)
        elif command == "months":
            current = parse_date(args[0] + "-01")
            count = int(args[1])
            if not 1 <= count <= 12:
                raise ValueError("Invalid CARBON_REPLAY_MONTHS (1..12)")
            for offset in range(count, 0, -1):
                year, month = divmod(current.year * 12 + current.month - 1 - offset, 12)
                print(date(year, month + 1, 1))
        elif command == "lock":
            timeout = float(args[0])
            if not math.isfinite(timeout) or timeout < 0:
                raise ValueError("Invalid FINOPS_LOCK_TIMEOUT")
            deadline = time.monotonic() + timeout
            while True:
                try:
                    # fd 9 is inherited from Bash; the parent keeps it open.
                    fcntl.flock(9, fcntl.LOCK_EX | fcntl.LOCK_NB)
                    return 0
                except BlockingIOError:
                    remaining = deadline - time.monotonic()
                    if remaining <= 0:
                        print("FinOps lock unavailable", file=sys.stderr)
                        return 75
                    time.sleep(min(0.25, remaining))
        else:
            raise ValueError("Unknown runtime command")
    except (ValueError, OSError, OverflowError) as exc:
        print(str(exc), file=sys.stderr)
        return 1
    return 0


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