import pytest
import subprocess
import os
from viperx.main import app

def run_command(cmd, cwd):
    """Run a shell command and return result."""
    return subprocess.run(
        cmd, 
        cwd=cwd, 
        check=True, 
        capture_output=True, 
        text=True
    )

INTEGRATION_CLASSIC_CONFIG = """
project:
  name: "int-classic"
settings:
  use_config: true
"""

INTEGRATION_WORKSPACE_CONFIG = """
project:
  name: "int-ws"
workspace:
  packages:
    - name: "int_pkg"
      use_config: true
"""

@pytest.mark.slow
def test_classic_lifecycle(runner, temp_workspace, mock_git_config, mock_builder_check):
    """
    Integration: Init -> Sync -> Run.
    """
    with open("viperx.yaml", "w") as f:
        f.write(INTEGRATION_CLASSIC_CONFIG)
        
    # 1. Init
    result = runner.invoke(app, ["config", "-c", "viperx.yaml"])
    assert result.exit_code == 0
    
    project_root = temp_workspace / "int_classic"
    assert project_root.exists()
    
    # 2. Sync
    # This downloads dependencies (pyyaml, etc). Might be slow.
    # We rely on 'uv' being in PATH.
    try:
        run_command(["uv", "sync"], cwd=project_root)
    except subprocess.CalledProcessError as e:
        pytest.fail(f"uv sync failed: {e.stderr}")
        
    # 3. Run Main
    # Result should be "Hi from int-classic!" (generated by defaults)
    try:
        run_res = run_command(["uv", "run", "int-classic"], cwd=project_root)
        assert "Hi from int-classic" in run_res.stdout # name in config is project name (int-classic)
    except subprocess.CalledProcessError as e:
        pytest.fail(f"uv run failed: {e.stderr}")


@pytest.mark.slow
def test_workspace_lifecycle(runner, temp_workspace, mock_git_config, mock_builder_check):
    """
    Integration: Init Workspace -> Sync -> Run Package.
    """
    with open("viperx.yaml", "w") as f:
        f.write(INTEGRATION_WORKSPACE_CONFIG)
        
    # 1. Init
    result = runner.invoke(app, ["config", "-c", "viperx.yaml"])
    assert result.exit_code == 0
    
    root = temp_workspace / "int_ws"
    assert root.exists()
    
    # 2. Sync (Root)
    try:
        run_command(["uv", "sync"], cwd=root)
    except subprocess.CalledProcessError as e:
        pytest.fail(f"uv sync failed: {e.stderr}")
        
    # 3. Run Package
    try:
        run_res = run_command(["uv", "run", "int_pkg"], cwd=root)
        assert "Hi from int_pkg" in run_res.stdout
    except subprocess.CalledProcessError as e:
        pytest.fail(f"uv run failed: {e.stderr}")
