"""Monthly cron orchestration with fake batch commands, never cloud or DB I/O."""

from __future__ import annotations

import fcntl
import json
import os
import subprocess
import sys
from pathlib import Path

import pytest

SCRIPT = Path(__file__).resolve().parents[1] / "scripts/run-finops-carbon-monthly.sh"


@pytest.fixture
def cron(tmp_path):
    commands = tmp_path / "commands"
    commands.mkdir()
    calls = tmp_path / "calls.jsonl"
    state = tmp_path / "state"
    state.mkdir()

    def executable(name, body):
        target = commands / name
        target.write_text(f"#!{sys.executable}\n" + body)
        target.chmod(0o755)
        return target

    batch = executable(
        "finops-batches",
        """import json, os, sys
assert os.environ.get('CARBON_TEST_CONFIG_LOADED') == 'yes'
with open(os.environ['CARBON_TEST_CALLS'], 'a') as output:
    output.write(json.dumps(sys.argv[1:]) + '\\n')
key = sys.argv[2] + '@' + sys.argv[4]
sys.exit(2 if key == os.environ.get('CARBON_TEST_FAIL') else 0)
""",
    )
    executable(
        "date",
        """import os, sys
if sys.argv[1:] == ['+%Y-%m']:
    print(os.environ['CARBON_TEST_MONTH'])
else:
    os.execv('/bin/date', ['date', *sys.argv[1:]])
""",
    )
    # macOS has no util-linux binary. Exercise the same flock system call on
    # inherited fd 9, including contention, rather than a no-op lock mock.
    executable(
        "flock",
        """import fcntl, sys
assert sys.argv[1:] == ['-n', '9']
try:
    fcntl.flock(9, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
    sys.exit(1)
""",
    )
    config = tmp_path / "batches.env"
    config.write_text('CARBON_TEST_CONFIG_LOADED="yes"\n')
    env = os.environ | {
        "PATH": str(commands) + os.pathsep + os.environ.get("PATH", ""),
        "FINOPS_ENV_FILE": str(config),
        "FINOPS_BIN": str(batch),
        "CARBON_REPLAY_MONTHS": "3",
        "CARBON_STATE_DIR": str(state),
        "CARBON_TEST_CALLS": str(calls),
        "CARBON_TEST_MONTH": "2026-11",
        "CARBON_TEST_FAIL": "",
    }

    def run(**overrides):
        result = subprocess.run(
            ["/bin/bash", str(SCRIPT)],
            env=env | overrides,
            capture_output=True,
            text=True,
            timeout=120,
            check=False,
        )
        records = (
            [json.loads(line) for line in calls.read_text().splitlines()]
            if calls.exists()
            else []
        )
        return result, records

    return run, state


@pytest.mark.parametrize(
    "current,expected",
    [
        ("2026-11", ["2026-08-01", "2026-09-01", "2026-10-01"]),
        ("2027-01", ["2026-10-01", "2026-11-01", "2026-12-01"]),
    ],
)
def test_calendar_window_and_sequential_chains(cron, current, expected):
    run, _ = cron
    result, calls = run(CARBON_TEST_MONTH=current)
    assert result.returncode == 0, result.stderr
    assert calls == [
        ["run", f"{provider}.carbon.{stage}.monthly", "--business-date", day]
        for day in expected
        for provider in ("gcp", "azure")
        for stage in ("bronze", "silver", "gold")
    ]
    assert "terminé avec succès" in result.stdout


def test_failure_stops_only_its_chain_and_returns_error(cron):
    run, _ = cron
    result, calls = run(CARBON_TEST_FAIL="gcp.carbon.silver.monthly@2026-09-01")
    assert result.returncode == 1
    assert len(calls) == 17
    assert [
        "run",
        "gcp.carbon.gold.monthly",
        "--business-date",
        "2026-09-01",
    ] not in calls
    assert [
        "run",
        "azure.carbon.gold.monthly",
        "--business-date",
        "2026-09-01",
    ] in calls
    assert calls[-1] == [
        "run",
        "azure.carbon.gold.monthly",
        "--business-date",
        "2026-10-01",
    ]
    assert "gcp@2026-09-01" in result.stderr


def test_concurrent_execution_is_rejected_without_running_batches(cron):
    run, state = cron
    with (state / "carbon-monthly.lock").open("w") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        result, calls = run()
    assert result.returncode == 75
    assert not calls
    assert "déjà en cours" in result.stderr


@pytest.mark.parametrize("months", ["0", "13", "invalid"])
def test_invalid_window_does_not_run_any_batch(cron, months):
    run, _ = cron
    result, calls = run(CARBON_REPLAY_MONTHS=months)
    assert result.returncode == 1 and not calls


def test_unreadable_environment_does_not_run_any_batch(cron):
    run, state = cron
    result, calls = run(FINOPS_ENV_FILE=str(state / "missing.env"))
    assert result.returncode == 1 and not calls
    assert "Configuration illisible" in result.stderr
