import subprocess
import json
import yaml

def test_create_session_dry_run(mam_sandbox, mock_herdr, mock_agents):
    """
    Sanity test verifying that create_session.sh --dry-run parses inputs,
    invokes herdr's preflight checks, and exits successfully without side effects.
    """
    tmp_path = mam_sandbox
    script_path = tmp_path / "skills" / "multi-agent-mux-create" / "scripts" / "create_session.sh"
    
    cmd = [
        "bash", str(script_path),
        "--workspace", str(tmp_path),
        "--agent", "claude",
        "--role", "Creator",
        "--dry-run"
    ]
    res = subprocess.run(cmd, capture_output=True, text=True)
    assert res.returncode == 0, f"Stdout: {res.stdout}\nStderr: {res.stderr}"
    assert "[dry-run] would spawn" in res.stdout

    # Verify that mock herdr was called for checking session existence (which gets translated to agent get)
    with open(mock_herdr, 'r') as f:
        state = json.load(f)
    
    calls = state.get("calls", [])
    assert any("agent" in call and "get" in call for call in calls), f"Calls: {calls}"

def test_create_session_full(mam_sandbox, mock_herdr, mock_agents):
    """
    Sanity test verifying that a full create_session.sh run intercepts herdr calls,
    completes the TUI readiness check using mock responses, and serializes state
    correctly to the sandboxed agent-sessions.yaml registry.
    """
    tmp_path = mam_sandbox
    script_path = tmp_path / "skills" / "multi-agent-mux-create" / "scripts" / "create_session.sh"
    
    cmd = [
        "bash", str(script_path),
        "--workspace", str(tmp_path),
        "--agent", "claude",
        "--role", "Creator"
    ]
    res = subprocess.run(cmd, capture_output=True, text=True)
    assert res.returncode == 0, f"Stdout: {res.stdout}\nStderr: {res.stderr}"
    
    # 1. Verify mock herdr state file registers the agent session
    with open(mock_herdr, 'r') as f:
        state = json.load(f)
    
    agents = state.get("agents", {})
    assert len(agents) == 1, "There should be exactly one registered agent in the mock herdr state."
    
    session_name = list(agents.keys())[0]
    from lib_py.agents.sanitize import sanitize_herdr_agent_name
    assert len(session_name) <= 32
    assert agents[session_name]["status"] == "running"
    assert agents[session_name]["agent"] == "claude"
    
    # 2. Verify that agent-sessions.yaml is successfully written
    yaml_path = tmp_path / ".mam" / "agent-sessions.yaml"
    assert yaml_path.exists(), "The agent-sessions.yaml configuration file was not created."
    
    with open(yaml_path, 'r') as f:
        reg = yaml.safe_load(f)
        
    sessions = reg.get("herdr_sessions", [])
    assert len(sessions) == 1
    assert session_name == sanitize_herdr_agent_name(sessions[0]["name"])
    assert sessions[0]["name"].endswith("-creator-claude")
    assert sessions[0]["status"] == "running"
    assert sessions[0]["role"] == "Creator"
