import { type Trace } from '@/types/trace'

/**
 * Extracts project and webapp information from a URL to create a unique local trace identifier.
 * @param url - The URL can be in one of these formats:
 *         - http://host/dip/api/webapps/view?projectKey=PROJECTKEY&webAppId=WEBAPPID (regular access)
 *         - http://host/webapps/PROJECTKEY/WEBAPPID/ (direct access)
 *         - http://host/webapps/CUSTOMURL/ (vanity URL)
 * @returns A string in the format 'trace_explorer_${projectKey}_${webAppId}_local_trace'
 *         or 'trace_explorer_${customUrl}_local_trace' for vanity URLs
 */
export function getLocalTraceItemName(url: string): string {
  const urlObj = new URL(url)
  const pathParts = urlObj.pathname.split('/').filter((part) => part.length > 0)

  // handle regular access pattern with query parameters
  if (url.includes('api/webapps/view')) {
    const projectKey = urlObj.searchParams.get('projectKey')
    const webAppId = urlObj.searchParams.get('webAppId')
    if (projectKey && webAppId) {
      return `trace_explorer_${projectKey}_${webAppId}_local_trace`
    }
  }

  // handle direct access pattern: /webapps/PROJECTKEY/WEBAPPID/
  if (pathParts[0] === 'webapps' && pathParts.length >= 3) {
    const projectKey = pathParts[1]
    const webAppId = pathParts[2]
    return `trace_explorer_${projectKey}_${webAppId}_local_trace`
  }

  // handle vanity URL pattern: /webapps/CUSTOMURL/
  if (pathParts[0] === 'webapps' && pathParts.length >= 2) {
    const customUrl = pathParts[1]
    return `trace_explorer_${customUrl}_local_trace`
  }

  // fallback for any other case
  return 'trace_explorer_local_trace'
}

export function getRawTraceFromLS(itemName: string): any {
  try {
    const stored = localStorage.getItem(itemName)

    if (stored) {
      return stored
    }
  } catch {
    console.error('Error loading local trace from storage')
  }

  return null
}

export function getTraceFromLS(itemName: string): Trace | undefined {
  try {
    const stored = localStorage.getItem(itemName)

    if (!stored) {
      return undefined
    }

    const parsed = JSON.parse(stored)
    if (parsed) {
      return parsed as Trace
    }
  } catch {
    console.error('Error loading local trace from storage')
  }

  return undefined
}

export function removeTraceFromLS() {
  const itemName = getLocalTraceItemName(window.location.href)
  localStorage.removeItem(itemName)
}
