import pytest
from unittest.mock import MagicMock, patch
import os
import threading
import time
import json
import requests
import sys

# Ensure project root is in path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from api_hook_client import ApiHookClient

def simulate_conductor_phase_completion(client: ApiHookClient):
    """
    Simulates the Conductor agent's logic for phase completion using ApiHookClient.
    """
    results = {
        "verification_successful": False,
        "verification_message": ""
    }
    
    try:
        status = client.get_status()
        if status.get('status') == 'ok':
            results["verification_successful"] = True
            results["verification_message"] = "Automated verification completed successfully."
        else:
            results["verification_successful"] = False
            results["verification_message"] = f"Automated verification failed: {status}"
    except Exception as e:
        results["verification_successful"] = False
        results["verification_message"] = f"Automated verification failed: {e}"

    return results

def test_conductor_integrates_api_hook_client_for_verification(live_gui):
    """
    Verify that Conductor's simulated phase completion logic properly integrates
    and uses the ApiHookClient for verification against the live GUI.
    """
    client = ApiHookClient()
    results = simulate_conductor_phase_completion(client)

    assert results["verification_successful"] is True
    assert "successfully" in results["verification_message"]

def test_conductor_handles_api_hook_failure(live_gui):
    """
    Verify Conductor handles a simulated API hook verification failure.
    We patch the client's get_status to simulate failure even with live GUI.
    """
    client = ApiHookClient()
    
    with patch.object(ApiHookClient, 'get_status') as mock_get_status:
        mock_get_status.return_value = {'status': 'failed', 'error': 'Something went wrong'}
        results = simulate_conductor_phase_completion(client)

        assert results["verification_successful"] is False
        assert "failed" in results["verification_message"]

def test_conductor_handles_api_hook_connection_error():
    """
    Verify Conductor handles a simulated API hook connection error (server down).
    """
    client = ApiHookClient(base_url="http://127.0.0.1:9998", max_retries=0)
    results = simulate_conductor_phase_completion(client)

    assert results["verification_successful"] is False
    # Check for expected error substrings from ApiHookClient
    msg = results["verification_message"]
    assert any(term in msg for term in ["Could not connect", "timed out", "Could not reach"])
