from pathlib import Path

from cotext_delta import cli


def test_cli_apply_patch_with_env(tmp_path, monkeypatch, capsys):
    env_file = tmp_path / ".env"
    env_file.write_text("MODEL=gpt-5\nOPENAI_API_KEY=sk-test\n", encoding="utf-8")
    patch_file = tmp_path / "patch.txt"
    patch_file.write_text(
        """*** Begin Patch
*** Add File: new.txt
+hello
*** End Patch""",
        encoding="utf-8",
    )
    exit_code = cli.main(
        ["--env", str(env_file), "apply_patch", "--file", str(patch_file), "--yes"]
    )
    assert exit_code == 0
    created = Path("new.txt")
    assert created.exists()
    created.unlink()
    captured = capsys.readouterr()
    assert "Applied patch" in captured.out or "Applied patch" in captured.err


def test_cli_provider_error(tmp_path, capsys):
    env_file = tmp_path / ".env"
    env_file.write_text("MODEL=oss-model\n", encoding="utf-8")
    exit_code = cli.main(["--env", str(env_file), "read_file", "--file", str(tmp_path / "no.txt")])
    assert exit_code == 1
    captured = capsys.readouterr()
    assert "Unable to determine provider" in captured.err


def test_cli_exec_runs_command(tmp_path, capsys):
    env_file = tmp_path / ".env"
    env_file.write_text("MODEL=gpt-5\nOPENAI_API_KEY=sk-test\n", encoding="utf-8")
    exit_code = cli.main(
        ["--env", str(env_file), "exec", "echo hi", "--workdir", str(tmp_path), "--yes", "--timeout", "10"]
    )
    assert exit_code == 0
    captured = capsys.readouterr()
    assert "hi" in captured.out or "hi" in captured.err


def test_cli_read_file_indent(tmp_path, capsys):
    env_file = tmp_path / ".env"
    env_file.write_text("MODEL=gpt-5\nOPENAI_API_KEY=sk-test\n", encoding="utf-8")
    target = tmp_path / "f.txt"
    target.write_text("  a\n  b\n", encoding="utf-8")
    exit_code = cli.main(["--env", str(env_file), "read_file", "--file", str(target), "--indent"])
    assert exit_code == 0
    captured = capsys.readouterr()
    assert "  a" in captured.out and "  b" in captured.out
