"""Windows / Unix shell argv 构造。"""

from __future__ import annotations

import sys

import pytest

from aicd.tools import process_tool as pt


def test_shell_argv_posix(monkeypatch) -> None:
    monkeypatch.setattr(sys, "platform", "linux")
    av = pt.shell_argv_from_user_input(command="echo hi")
    assert av == ["/bin/sh", "-c", "echo hi"]


def test_shell_argv_posix_direct_argv(monkeypatch) -> None:
    monkeypatch.setattr(sys, "platform", "linux")
    av = pt.shell_argv_from_user_input(argv=["/bin/echo", "a b"])
    assert av == ["/bin/echo", "a b"]


def test_shell_argv_windows_cmd(monkeypatch) -> None:
    monkeypatch.setattr(sys, "platform", "win32")
    monkeypatch.setenv("ComSpec", r"C:\Windows\System32\cmd.exe")
    av = pt.shell_argv_from_user_input(command="dir")
    assert av[0].lower().endswith("cmd.exe")
    assert av[1] == "/d"
    assert av[2] == "/c"
    assert "chcp 65001" in av[3]
    assert av[3].endswith("& dir") or "& dir" in av[3]


def test_shell_argv_windows_powershell(monkeypatch) -> None:
    monkeypatch.setattr(sys, "platform", "win32")
    av = pt.shell_argv_from_user_input(command="Get-Location", shell="powershell")
    assert av[0].lower().endswith("powershell.exe") or "powershell" in av[0].lower()
    assert "-Command" in av
    assert av[-1] == "Get-Location"


def test_shell_argv_errors() -> None:
    with pytest.raises(ValueError, match="non-empty"):
        pt.shell_argv_from_user_input(command="   ")
    with pytest.raises(ValueError, match="argv"):
        pt.shell_argv_from_user_input(argv=[])


def test_default_shell_argv_alias(monkeypatch) -> None:
    monkeypatch.setattr(sys, "platform", "linux")
    assert pt.default_shell_argv("x") == ["/bin/sh", "-c", "x"]
