import sys
import os
import time
from pathlib import Path

# Add project root to sys.path
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if project_root not in sys.path:
 sys.path.append(project_root)

from src.performance_monitor import get_monitor
from src.aggregate import build_file_items
from src.dag_engine import TrackDAG
from src.models import Ticket

def run_aggregation_profile():
 monitor = get_monitor()
 base_dir = Path(project_root)
 # Get 30 python files for profiling
 files = [str(p.relative_to(base_dir)) for p in base_dir.glob("src/*.py")][:30]
 with monitor.scope("aggregation"):
  build_file_items(base_dir, files)

def run_dag_profile():
 monitor = get_monitor()
 tickets = []
 # Create 60 tickets with multiple dependencies to simulate complexity
 for i in range(60):
  deps = []
  if i > 0: deps.append(f"ticket_{i-1}")
  if i > 5: deps.append(f"ticket_{i-5}")
  if i > 10: deps.append(f"ticket_{i-10}")
  tickets.append(Ticket(
   id=f"ticket_{i}",
   description=f"Ticket {i}",
   depends_on=deps
  ))
 dag = TrackDAG(tickets)
 with monitor.scope("dag_operations"):
  # Run operations 50 times per profile call
  for _ in range(50):
   dag.topological_sort()
   dag.has_cycle()

def print_metrics():
 monitor = get_monitor()
 metrics = monitor.get_metrics()
 print(f"{'Component':<30} | {'Avg (ms)':<12} | {'Count':<8} | {'Max (ms)':<12} | {'Min (ms)':<12}")
 print("-" * 85)
 # Collect all base component names
 components = set()
 for key in metrics.keys():
  if key.startswith("time_") and key.endswith("_ms") and not key.endswith("_avg"):
   components.add(key[5:-3])
 
 for comp in sorted(list(components)):
  avg = metrics.get(f"time_{comp}_ms_avg", 0.0)
  count = int(metrics.get(f"count_{comp}", 0))
  max_val = metrics.get(f"max_{comp}_ms", 0.0)
  min_val = metrics.get(f"min_{comp}_ms", 0.0)
  print(f"{comp:<30} | {avg:<12.4f} | {count:<8} | {max_val:<12.4f} | {min_val:<12.4f}")

def main():
 monitor = get_monitor()
 monitor.enabled = True
 print("Starting Profiling Baseline...")
 print("Running aggregation profile (5 iterations)...")
 for _ in range(5):
  run_aggregation_profile()
 print("Running DAG profile (5 iterations)...")
 for _ in range(5):
  run_dag_profile()
 print("\nBaseline Performance Metrics:")
 print_metrics()
 monitor.stop()

if __name__ == "__main__":
 main()
