from __future__ import annotations

import json
from datetime import datetime, timedelta, timezone
from pathlib import Path

from argus.ray.discovery import build_head_record, load_head_record


def test_load_head_record_rejects_missing(tmp_path: Path):
    assert load_head_record(str(tmp_path / "nope.json")) is None


def test_load_head_record_rejects_expired(tmp_path: Path):
    p = tmp_path / "head.json"
    now = datetime.now(timezone.utc).replace(microsecond=0)
    rec = build_head_record(cluster_name="c", head_ip="1.2.3.4", ttl_s=1, now=now)
    p.write_text(json.dumps(rec.to_dict()), encoding="utf-8")
    assert load_head_record(str(p), now=now + timedelta(seconds=2)) is None


def test_load_head_record_accepts_fresh(tmp_path: Path):
    p = tmp_path / "head.json"
    now = datetime.now(timezone.utc).replace(microsecond=0)
    rec = build_head_record(cluster_name="c", head_ip="1.2.3.4", ttl_s=60, now=now)
    p.write_text(json.dumps(rec.to_dict()), encoding="utf-8")
    got = load_head_record(str(p), now=now + timedelta(seconds=1))
    assert got is not None
    assert got.head_addr() == "1.2.3.4:6379"


def test_head_publisher_main_once_writes_file(tmp_path: Path):
    from argus.ray import head_publisher as mod

    p = tmp_path / "head.json"
    rc = mod.main(
        [
            "--cluster-name",
            "c",
            "--head-ip-file",
            str(p),
            "--head-ip",
            "9.9.9.9",
            "--ttl-s",
            "60",
            "--once",
        ]
    )
    assert rc == 0
    assert "9.9.9.9" in p.read_text(encoding="utf-8")
