/**
 * Hook for loading infrastructure data from JSON files via API route
 * Uses React Query for caching, retry logic, and state management
 */

import { useQuery } from '@tanstack/react-query'
import type {
  Country,
  NetworkTopology,
  ComplianceRequirement,
  DeploymentMilestone,
  CostEstimate,
  InfrastructureSummary,
} from '../types/infrastructure'

// Data files are served via API route
const DATA_BASE_PATH = '/api/infrastructure/data'

// API response type
interface APIResponse<T> {
  data: T[]
  metadata: {
    filename: string
    lastModified: string
    size: number
  }
}

// Fetch JSON data from API route with error handling
async function fetchJSONData<T>(filename: string): Promise<T[]> {
  const response = await fetch(`${DATA_BASE_PATH}/${filename}`)
  
  if (!response.ok) {
    if (response.status === 404) {
      console.warn(`File not found: ${filename}`)
      return []
    }
    throw new Error(`Failed to load ${filename}: ${response.statusText}`)
  }
  
  const result: APIResponse<T> = await response.json()
  return result.data || []
}

export function useCountries(filter?: {
  region?: string
  priority?: string
  relationshipType?: string
}) {
  const { data, isLoading, error, isError } = useQuery({
    queryKey: ['countries', filter],
    queryFn: () => fetchJSONData<Country>('smom_countries.json'),
    staleTime: 5 * 60 * 1000, // 5 minutes
    retry: 3,
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
  })

  // Apply filters to the data
  const countries = data
    ? data.filter((c) => {
        if (filter?.region && c.region !== filter.region) return false
        if (filter?.priority && c.priority !== filter.priority) return false
        if (filter?.relationshipType && c.relationshipType !== filter.relationshipType) return false
        return true
      })
    : []

  return {
    countries,
    loading: isLoading,
    error: isError ? (error instanceof Error ? error : new Error('Failed to load countries')) : null,
  }
}

export function useNetworkTopologies(filter?: { region?: string; entity?: string }) {
  const { data, isLoading, error, isError } = useQuery({
    queryKey: ['networkTopologies', filter],
    queryFn: () => fetchJSONData<NetworkTopology>('network_topology.json'),
    staleTime: 5 * 60 * 1000,
    retry: 3,
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
  })

  const topologies = data
    ? data.filter((t) => {
        if (filter?.region && t.region !== filter.region) return false
        if (filter?.entity && t.entity !== filter.entity) return false
        return true
      })
    : []

  return {
    topologies,
    loading: isLoading,
    error: isError ? (error instanceof Error ? error : new Error('Failed to load topologies')) : null,
  }
}

export function useComplianceRequirements(filter?: {
  country?: string
  region?: string
  status?: string
  framework?: string
}) {
  const { data, isLoading, error, isError } = useQuery({
    queryKey: ['complianceRequirements', filter],
    queryFn: () => fetchJSONData<ComplianceRequirement>('compliance_requirements.json'),
    staleTime: 5 * 60 * 1000,
    retry: 3,
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
  })

  const requirements = data
    ? data.filter((r) => {
        if (filter?.country && r.country !== filter.country) return false
        if (filter?.region && r.region !== filter.region) return false
        if (filter?.status && r.status !== filter.status) return false
        if (filter?.framework && !r.frameworks.includes(filter.framework)) return false
        return true
      })
    : []

  return {
    requirements,
    loading: isLoading,
    error: isError
      ? (error instanceof Error ? error : new Error('Failed to load compliance requirements'))
      : null,
  }
}

export function useDeploymentMilestones(filter?: {
  region?: string
  entity?: string
  priority?: string
  status?: string
}) {
  const { data, isLoading, error, isError } = useQuery({
    queryKey: ['deploymentMilestones', filter],
    queryFn: () => fetchJSONData<DeploymentMilestone>('deployment_timeline.json'),
    staleTime: 5 * 60 * 1000,
    retry: 3,
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
  })

  const milestones = data
    ? data.filter((m) => {
        if (filter?.region && m.region !== filter.region) return false
        if (filter?.entity && m.entity !== filter.entity) return false
        if (filter?.priority && m.priority !== filter.priority) return false
        if (filter?.status && m.status !== filter.status) return false
        return true
      })
    : []

  return {
    milestones,
    loading: isLoading,
    error: isError
      ? (error instanceof Error ? error : new Error('Failed to load milestones'))
      : null,
  }
}

export function useCostEstimates(filter?: {
  region?: string
  entity?: string
  category?: string
}) {
  const { data, isLoading, error, isError } = useQuery({
    queryKey: ['costEstimates', filter],
    queryFn: () => fetchJSONData<CostEstimate>('cost_estimates.json'),
    staleTime: 5 * 60 * 1000,
    retry: 3,
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
  })

  const estimates = data
    ? data.filter((e) => {
        if (filter?.region && e.region !== filter.region) return false
        if (filter?.entity && e.entity !== filter.entity) return false
        if (filter?.category && e.category !== filter.category) return false
        return true
      })
    : []

  return {
    estimates,
    loading: isLoading,
    error: isError
      ? (error instanceof Error ? error : new Error('Failed to load cost estimates'))
      : null,
  }
}

export function useInfrastructureSummary() {
  const { data: countries, isLoading: countriesLoading } = useQuery({
    queryKey: ['countries'],
    queryFn: () => fetchJSONData<Country>('smom_countries.json'),
    staleTime: 5 * 60 * 1000,
  })

  const { data: milestones, isLoading: milestonesLoading } = useQuery({
    queryKey: ['deploymentMilestones'],
    queryFn: () => fetchJSONData<DeploymentMilestone>('deployment_timeline.json'),
    staleTime: 5 * 60 * 1000,
  })

  const { data: estimates, isLoading: estimatesLoading } = useQuery({
    queryKey: ['costEstimates'],
    queryFn: () => fetchJSONData<CostEstimate>('cost_estimates.json'),
    staleTime: 5 * 60 * 1000,
  })

  const loading = countriesLoading || milestonesLoading || estimatesLoading

  // Calculate summary from loaded data
  const summary: InfrastructureSummary | null =
    countries && milestones && estimates
      ? (() => {
          const regions = new Set(countries.map((c) => c.region))
          const totalCost = estimates.reduce((sum, e) => sum + e.annual, 0)

          const progress = milestones.reduce(
            (acc, m) => {
              acc[m.status] = (acc[m.status] || 0) + 1
              return acc
            },
            {} as Record<string, number>
          )

          return {
            totalCountries: countries.length,
            totalRegions: regions.size,
            totalCost,
            deploymentProgress: {
              planned: progress.Planned || 0,
              inProgress: progress['In Progress'] || 0,
              complete: progress.Complete || 0,
              blocked: progress.Blocked || 0,
            },
          }
        })()
      : null

  return { summary, loading, error: null }
}

