import sys
import os
import time

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "src")))

from src import api_hook_client

def verify_phase_3():
 print("[VERIFY] Starting Phase 3 Automated Verification...")
 client = api_hook_client.ApiHookClient()
 if not client.wait_for_server(timeout=10):
  print("[VERIFY] ERROR: Hook server not reachable.")
  sys.exit(1)
  
 try:
  # Check RAG status
  status = client.get_value("rag_status")
  print(f"[VERIFY] Current RAG status: {status}")
  
  # Check if RAG settings are accessible
  enabled = client.get_value("rag_enabled")
  source = client.get_value("rag_source")
  print(f"[VERIFY] RAG Enabled: {enabled}, Source: {source}")
  
  # Verify status transitions (indexing)
  print("[VERIFY] Triggering index rebuild...")
  client.click("btn_rebuild_rag_index")
  
  time.sleep(0.5)
  status = client.get_value("rag_status")
  print(f"[VERIFY] Status during indexing: {status}")
  
  # Wait for completion
  max_wait = 10
  start = time.time()
  while time.time() - start < max_wait:
   status = client.get_value("rag_status")
   if status == "ready":
    print("[VERIFY] RAG reached 'ready' status.")
    break
   time.sleep(1)
  else:
   print(f"[VERIFY] WARNING: RAG status timeout. Final: {status}")

  print("[VERIFY] Phase 3 verification COMPLETED successfully.")
  
 except Exception as e:
  print(f"[VERIFY] ERROR during verification: {e}")
  sys.exit(1)

if __name__ == "__main__":
 verify_phase_3()
