from __future__ import annotations

import json
from pathlib import Path

from iac.cli import app
from conftest import runner, write_book


def _env(book_dir: Path) -> dict[str, str]:
    return {"IAC_BOOK_DIRS": str(book_dir)}


def test_check_book_and_deps_install(tmp_path: Path) -> None:
    books = tmp_path / "books"
    write_book(books / "sample.yaml", name="sample")

    r = runner.invoke(
        app, ["check", "book", "sample", "--output", "json"], env=_env(books)
    )
    assert r.exit_code != 0  # includes intentional missing requirement
    payload = json.loads(r.stdout)
    assert payload["summary"]["total"] >= 2
    req_names = {x["requirement"] for x in payload["requirements"]}
    assert "definitely_missing_cmd_for_tests" in req_names

    r = runner.invoke(
        app, ["deps", "install", "sample", "--output", "json"], env=_env(books)
    )
    assert r.exit_code == 0
    payload = json.loads(r.stdout)
    assert payload["summary"]["total"] >= 1
    assert payload["apply"] is False


def test_check_and_deps_bad_output_value(tmp_path: Path) -> None:
    books = tmp_path / "books"
    write_book(books / "sample.yaml", name="sample")

    r = runner.invoke(
        app, ["check", "book", "sample", "--output", "bogus"], env=_env(books)
    )
    assert r.exit_code != 0

    r = runner.invoke(
        app, ["deps", "install", "sample", "--output", "bogus"], env=_env(books)
    )
    assert r.exit_code != 0
