"""Tests for the CLI interface."""

import tempfile
import json
from pathlib import Path

from click.testing import CliRunner

from schemai.cli import cli


def test_infer_json_command():
    """Test the infer command with JSON file."""
    data = {
        "name": "Alice",
        "age": 30,
        "email": "alice@example.com",
    }
    
    with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
        json.dump(data, f)
        temp_path = f.name
    
    try:
        runner = CliRunner()
        result = runner.invoke(cli, ["infer", temp_path, "-n", "User"])
        
        assert result.exit_code == 0
        assert "class User(BaseModel)" in result.output
        assert "name" in result.output
        assert "age" in result.output
    finally:
        Path(temp_path).unlink()


def test_infer_with_output_file():
    """Test the infer command with output file."""
    data = {"name": "Bob", "active": True}
    
    with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
        json.dump(data, f)
        temp_path = f.name
    
    with tempfile.TemporaryDirectory() as tmpdir:
        output_path = Path(tmpdir) / "schema.py"
        
        try:
            runner = CliRunner()
            result = runner.invoke(
                cli,
                ["infer", temp_path, "-n", "Model", "-o", str(output_path)],
            )
            
            assert result.exit_code == 0
            assert output_path.exists()
            content = output_path.read_text()
            assert "class Model(BaseModel)" in content
        finally:
            Path(temp_path).unlink()


def test_info_command():
    """Test the info command."""
    data = {"id": 1, "name": "Test"}
    
    with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
        json.dump(data, f)
        temp_path = f.name
    
    try:
        runner = CliRunner()
        result = runner.invoke(cli, ["info", temp_path])
        
        assert result.exit_code == 0
        assert "File:" in result.output
        assert "Inferred Fields:" in result.output
    finally:
        Path(temp_path).unlink()


if __name__ == "__main__":
    import pytest
    pytest.main([__file__, "-v"])
