import pytest
import time
import sys
import os

# 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

@pytest.mark.integration
def test_full_live_workflow(live_gui):
    """
    Integration test that drives the GUI through a full workflow.
    """
    client = ApiHookClient()
    assert client.wait_for_server(timeout=10)
    client.post_session(session_entries=[])
    time.sleep(2)

    # 1. Reset
    client.click("btn_reset")
    time.sleep(1)

    # 2. Project Setup
    temp_project_path = os.path.abspath("tests/temp_project.toml")
    if os.path.exists(temp_project_path):
        os.remove(temp_project_path)
        
    client.click("btn_project_new_automated", user_data=temp_project_path)
    time.sleep(1) # Wait for project creation and switch
    
    # Verify metadata update
    proj = client.get_project()
    
    test_git = os.path.abspath(".")
    client.set_value("project_git_dir", test_git)
    client.click("btn_project_save")
    time.sleep(1)
    
    proj = client.get_project()
    # flat_config returns {"project": {...}, "output": ...} 
    # so proj is {"project": {"project": {"git_dir": ...}}}
    assert proj['project']['project']['git_dir'] == test_git

    # Enable auto-add so the response ends up in history
    client.set_value("auto_add_history", True)
    client.set_value("current_model", "gemini-2.5-flash-lite")
    time.sleep(0.5)

    # 3. Discussion Turn
    client.set_value("ai_input", "Hello! This is an automated test. Just say 'Acknowledged'.")
    client.click("btn_gen_send")

    # Verify thinking indicator appears (might be brief)
    thinking_seen = False
    print("\nPolling for thinking indicator...")
    for i in range(40):
        state = client.get_indicator_state("thinking_indicator")
        if state.get('shown'):
            thinking_seen = True
            print(f"Thinking indicator seen at poll {i}")
            break
        time.sleep(0.5)

    # 4. Wait for response in session
    success = False
    print("Waiting for AI response in session...")
    for i in range(120):
        session = client.get_session()
        entries = session.get('session', {}).get('entries', [])
        if any(e.get('role') == 'AI' for e in entries):
            success = True
            print(f"AI response found at second {i}")
            break
        time.sleep(1)

    assert success, "AI failed to respond within 120 seconds"
    # 5. Switch Discussion
    client.set_value("disc_new_name_input", "AutoDisc")
    client.click("btn_disc_create")
    time.sleep(1.0) # Wait for GUI to process creation
    
    client.select_list_item("disc_listbox", "AutoDisc")
    time.sleep(1.0) # Wait for GUI to switch
    
    # Verify session is empty in new discussion
    session = client.get_session()
    assert len(session.get('session', {}).get('entries', [])) == 0
