from __future__ import annotations

import sys
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "plugins" / "1c"))

from parser.scheduled_job import decode_schedule, schedule_write_edits  # noqa: E402


def atom(value: Any) -> dict[str, Any]:
    return {"type": "atom", "value": str(value)}


def schedule_tree() -> dict[str, Any]:
    return {
        "type": "list",
        "items": [
            atom("00010101000000"),
            atom("00010101000000"),
            atom("00010101090000"),
            atom("00010101180000"),
            atom("00010101000000"),
            atom(0),
            atom(0),
            atom(0),
            atom(2),
            atom(1),
            atom(5),
            atom(0),
            atom(0),
            atom(1),
            atom(1),
            atom(1),
            atom(1),
        ],
    }


def test_decode_schedule_is_adapter_independent() -> None:
    result = decode_schedule(schedule_tree())

    assert result["status"] == "ok"
    assert result["begin_time"] == "09:00:00"
    assert result["end_time"] == "18:00:00"
    assert result["week_days"] == [1, 5]
    assert result["months"] == [1]


def test_schedule_write_edits_rebuilds_resized_collections() -> None:
    result = schedule_write_edits(
        schedule_tree(),
        {"week_days": [1, 2, 3, 4, 5], "months": [1, 6, 12]},
    )

    assert result["status"] == "ok"
    assert result["counts"]["resized_collections"] == 2
    rebuilt = decode_schedule(result["edits"][0]["replace_root"])
    assert rebuilt["week_days"] == [1, 2, 3, 4, 5]
    assert rebuilt["months"] == [1, 6, 12]


def test_schedule_write_edits_rejects_unknown_named_field() -> None:
    result = schedule_write_edits(schedule_tree(), {"sql_path": "1.2.3"})

    assert result["status"] == "invalid_argument"
    assert result["error"] == "unsupported_schedule_fields"
    assert result["diagnostics"]["fields"] == ["sql_path"]
