from __future__ import annotations

import importlib.util
from pathlib import Path

import pytest


ROOT = Path(__file__).resolve().parents[1]
MODULE_PATH = ROOT / "skills" / "jyotish-full-synastry-reading" / "scripts" / "prepare_full_synastry_packets.py"
spec = importlib.util.spec_from_file_location("prepare_full_synastry_packets", MODULE_PATH)
module = importlib.util.module_from_spec(spec)
assert spec and spec.loader
spec.loader.exec_module(module)


def _profile(**updates):
    profile = {
        "date": "2000-01-01", "time": "12:34:56", "place": "Example City, Example Country",
        "latitude": 31.2, "longitude": 121.5, "timezone": 8.0,
        "ayanamsa": "lahiri", "node_mode": "mean",
    }
    profile.update(updates)
    return profile


def test_profile_normalization_requires_place_and_builds_native_full_reading_command():
    profile = module.normalize_profile(_profile())
    command = module.full_reading_command(profile, today="2026-10-17")
    assert command[2] == "full-reading"
    assert command[command.index("--ayanamsa") + 1] == "lahiri"
    assert command[command.index("--node-mode") + 1] == "mean"
    assert command[command.index("--today") + 1] == "2026-10-17"
    with pytest.raises(ValueError, match="place"):
        module.normalize_profile(_profile(place=""))


def test_runner_has_a_fixed_preflight_before_native_calculation():
    command = module.preflight_command()
    assert command[1].endswith("scripts/pre_work_check.py")
    assert command[command.index("--remote-timeout") + 1] == "8"
    assert command[command.index("--command-timeout") + 1] == "45"


def test_profile_normalization_accepts_minute_precision_and_rejects_invalid_nodes():
    profile = module.normalize_profile(_profile(time="12:34"))
    assert profile["second"] == 0
    with pytest.raises(ValueError, match="node_mode"):
        module.normalize_profile(_profile(node_mode="hybrid"))


def test_private_output_directory_refuses_repository_paths(tmp_path):
    assert module._private_output_directory(str(tmp_path)) == tmp_path.resolve()
    with pytest.raises(ValueError, match="outside the repository"):
        module._private_output_directory(str(ROOT / "outputs"))


def test_runner_points_to_the_gated_bilingual_delivery_compiler():
    source = MODULE_PATH.read_text(encoding="utf-8")
    assert "compose_full_synastry_delivery.py" in source
    assert "Write independent Chinese and English section payloads" in source
