import json
import pytest
from unittest.mock import patch, MagicMock
from io import StringIO
from pathlib import Path

from runtime.cli import cmd_pipe
from runtime.config import RuntimeConfig

@pytest.fixture
def mock_config(tmp_path):
    config = RuntimeConfig(data_dir=tmp_path, local_port=8003)
    return config

def test_cmd_pipe_no_stdin(capsys, mock_config):
    # Mock sys.stdin.isatty to return True
    with patch("sys.stdin.isatty", return_value=True):
        args = MagicMock()
        result = cmd_pipe(args, mock_config)
        assert result == 1
        captured = capsys.readouterr()
        assert "Error: No input provided on stdin" in captured.err

def test_cmd_pipe_runtime_not_running(capsys, mock_config):
    with patch("sys.stdin.isatty", return_value=False), \
         patch("sys.stdin.read", return_value="test prompt"), \
         patch("runtime.cli._is_runtime_running", return_value=False):
        args = MagicMock()
        result = cmd_pipe(args, mock_config)
        assert result == 1
        captured = capsys.readouterr()
        assert "Runtime server is not running" in captured.err

def test_cmd_pipe_success(capsys, mock_config):
    with patch("sys.stdin.isatty", return_value=False), \
         patch("sys.stdin.read", return_value="test prompt"), \
         patch("runtime.cli._is_runtime_running", return_value=True), \
         patch("runtime.cli._runtime_post") as mock_post:
         
        mock_post.return_value = {
            "success": True,
            "steps": [{"content": "test output", "model": "claude"}]
        }
        
        args = MagicMock()
        args.model = None
        args.strategy = None
        args.json = False
        args.format = None
        args.delimiter = "\n"

        result = cmd_pipe(args, mock_config)
        assert result == 0
        captured = capsys.readouterr()
        assert "test output" in captured.out

def test_cmd_pipe_json_output(capsys, mock_config):
    with patch("sys.stdin.isatty", return_value=False), \
         patch("sys.stdin.read", return_value="test prompt"), \
         patch("runtime.cli._is_runtime_running", return_value=True), \
         patch("runtime.cli._runtime_post") as mock_post:
         
        mock_post.return_value = {
            "success": True,
            "steps": [{"content": "test output", "model": "claude"}]
        }
        
        args = MagicMock()
        args.model = "claude"
        args.strategy = "single"
        args.json = True
        args.format = None
        args.delimiter = "\n"

        result = cmd_pipe(args, mock_config)
        assert result == 0
        captured = capsys.readouterr()
        out_data = json.loads(captured.out)
        assert out_data["input"] == "test prompt"
        assert out_data["output"] == "test output"
        assert out_data["model"] == "claude"
        assert "tokens" in out_data
        assert "latency_ms" in out_data
