import sys
import os
from pathlib import Path

# Fix sys.path
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(current_dir)
src_dir = os.path.join(project_root, "src")

for d in [project_root, src_dir]:
    if d not in sys.path:
        sys.path.insert(0, d)

# Ensure thirdparty is in sys.path
thirdparty = os.path.join(project_root, "thirdparty")
if thirdparty not in sys.path:
    sys.path.insert(0, thirdparty)

import asyncio
from simulation.sim_base import BaseSimulation, run_sim
from src.gui_2 import App
from src.models import FileItem

class VerifyTrackFixesSim(BaseSimulation):
    async def run(self):
        app = self.app
        print("[Sim] Starting verification of track fixes...")
        
        # 1. Setup a test file in context
        test_file = os.path.abspath("src/aggregate.py")
        f_item = FileItem(path=test_file)
        app.context_files = [f_item]
        app.controller.context_files = app.context_files
        
        await asyncio.sleep(0.5)
        
        # 2. Verify AST Inspector
        print("[Sim] Testing AST Inspector...")
        app.ui_inspecting_ast_file = f_item
        app._show_ast_inspector = True
        await asyncio.sleep(0.5)
        
        # Check if nodes were cached
        if app._cached_ast_nodes:
            print(f"[Sim] SUCCESS: AST nodes cached ({len(app._cached_ast_nodes)} nodes)")
        else:
            print("[Sim] FAILURE: No AST nodes cached")

        # 3. Verify Slice Editor
        print("[Sim] Testing Slice Editor...")
        app.ui_editing_slices_file = f_item
        app.text_viewer_title = f"Slices: {test_file}"
        from src import mcp_client
        app.text_viewer_content = mcp_client.read_file(test_file)
        app.text_viewer_type = "python"
        app.show_text_viewer = True
        app.show_windows["Text Viewer"] = True
        await asyncio.sleep(0.5)
        
        # Test Auto-Populate button
        print("[Sim] Testing Auto-Populate AST Slices...")
        app._populate_auto_slices(f_item)
        if f_item.custom_slices:
            print(f"[Sim] SUCCESS: Auto-slices populated ({len(f_item.custom_slices)} slices)")
        else:
            print("[Sim] FAILURE: No auto-slices populated")
            
        # 4. Verify Context Preview
        print("[Sim] Testing Context Preview...")
        app.context_preview_text = app.controller._do_generate()[0]
        if "## Files" in app.context_preview_text and "aggregate.py" in app.context_preview_text:
            print("[Sim] SUCCESS: Context preview generated with content")
        else:
            print(f"[Sim] FAILURE: Context preview text length: {len(app.context_preview_text)}")

        print("[Sim] Verification finished.")
        self.stop()

if __name__ == "__main__":
    os.environ['SLOP_TEST_HOOKS'] = '1'
    run_sim(VerifyTrackFixesSim)