import type { HTTPRequest } from '../types/httpRequest'

/**
 * Assigns connection numbers and request numbers to HTTP requests based on:
 * 1. Actual connectionId from Chrome DevTools trace data
 * 2. Sequential numbering (1, 2, 3...) based on chronological first-seen order
 * 3. Request ordering within each connection by start time
 */
export const assignConnectionNumbers = (requests: HTTPRequest[]): HTTPRequest[] => {
  // Sort all requests by start time to process in chronological order
  const chronologicalRequests = [...requests].sort((a, b) => a.timing.start - b.timing.start)
  
  // Track first-seen order of connection IDs
  const connectionIdToNumber = new Map<number, number>()
  let nextConnectionNumber = 1
  
  // First pass: assign connection numbers based on first-seen order
  chronologicalRequests.forEach(request => {
    if (request.connectionId !== undefined && !connectionIdToNumber.has(request.connectionId)) {
      connectionIdToNumber.set(request.connectionId, nextConnectionNumber++)
    }
  })
  
  // Group requests by connectionId and sort within each connection by start time
  const requestsByConnection = new Map<number, HTTPRequest[]>()
  const requestsWithoutConnection: HTTPRequest[] = []
  
  requests.forEach(request => {
    if (request.connectionId !== undefined) {
      if (!requestsByConnection.has(request.connectionId)) {
        requestsByConnection.set(request.connectionId, [])
      }
      requestsByConnection.get(request.connectionId)!.push(request)
    } else {
      requestsWithoutConnection.push(request)
    }
  })
  
  // Sort requests within each connection by start time
  requestsByConnection.forEach(connectionRequests => {
    connectionRequests.sort((a, b) => a.timing.start - b.timing.start)
  })
  
  // Assign connection numbers and request numbers
  const processedRequests = requests.map(request => {
    if (request.connectionId !== undefined) {
      const connectionNumber = connectionIdToNumber.get(request.connectionId) || 0
      const connectionRequests = requestsByConnection.get(request.connectionId) || []
      const requestNumberOnConnection = connectionRequests.findIndex(r => r.requestId === request.requestId) + 1
      
      return {
        ...request,
        connectionNumber,
        requestNumberOnConnection
      }
    } else {
      // Handle requests without connection ID (show as unknown)
      return {
        ...request,
        connectionNumber: undefined,
        requestNumberOnConnection: undefined
      }
    }
  })
  
  return processedRequests
}