"""Tests for the dynojson CLI."""

import json
import subprocess
import sys


def _run_cli(*args: str, stdin: str | None = None) -> subprocess.CompletedProcess:
    """Run the dynojson CLI and return the CompletedProcess."""
    return subprocess.run(
        [sys.executable, "-m", "dynojson.cli", *args],
        input=stdin,
        capture_output=True,
        text=True,
    )


class TestCLI:
    """Tests for the dynojson command-line interface."""

    def test_marshall_inline_json(self):
        result = _run_cli("marshall", '{"name":"Alice"}')
        assert result.returncode == 0
        output = json.loads(result.stdout.strip())
        assert output == {"name": {"S": "Alice"}}

    def test_marshall_alias_m(self):
        result = _run_cli("m", '{"count":5}')
        assert result.returncode == 0
        output = json.loads(result.stdout.strip())
        assert output == {"count": {"N": "5"}}

    def test_unmarshall_inline_json(self):
        result = _run_cli("unmarshall", '{"name":{"S":"Alice"}}')
        assert result.returncode == 0
        output = json.loads(result.stdout.strip())
        assert output == {"name": "Alice"}

    def test_unmarshall_alias_u(self):
        result = _run_cli("u", '{"count":{"N":"5"}}')
        assert result.returncode == 0
        output = json.loads(result.stdout.strip())
        assert output == {"count": 5}

    def test_stdin_unmarshall(self):
        ddb_json = '{"name":{"S":"Bob"},"age":{"N":"30"}}'
        result = _run_cli("u", "-", stdin=ddb_json)
        assert result.returncode == 0
        output = json.loads(result.stdout.strip())
        assert output == {"name": "Bob", "age": 30}

    def test_get_property(self):
        scan_json = '{"Items":[{"type":{"S":"fruit"}}]}'
        result = _run_cli("u", "-g", "Items", scan_json)
        assert result.returncode == 0
        output = json.loads(result.stdout.strip())
        assert output == [{"type": "fruit"}]

    def test_no_command_shows_help(self):
        result = _run_cli()
        assert result.returncode == 0

    def test_version_flag(self):
        result = _run_cli("--version")
        assert result.returncode == 0
        assert "dynojson" in result.stdout

    def test_invalid_json_returns_error(self):
        result = _run_cli("m", "not-a-file-or-json")
        assert result.returncode == 1
        assert "Error" in result.stderr
