import * as fs from 'fs'
import * as path from 'path'
import { fileURLToPath } from 'url'
// Note: Resolvers type will be generated from schema
// For now using any to avoid type errors
type Resolvers = any

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const PROJECT_ROOT = path.resolve(__dirname, '../..')
const DATA_DIR = path.join(PROJECT_ROOT, 'docs/infrastructure/data')

// Load JSON data files
function loadJSONFile<T>(filename: string): T[] {
  const filepath = path.join(DATA_DIR, filename)
  if (!fs.existsSync(filepath)) {
    return []
  }
  const content = fs.readFileSync(filepath, 'utf-8')
  return JSON.parse(content)
}

export const infrastructureResolvers: Resolvers = {
  Query: {
    countries: async (_, { filter }) => {
      const countries = loadJSONFile<any>('smom_countries.json')
      if (!filter) return countries

      return countries.filter((c: any) => {
        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
      })
    },

    country: async (_, { name }) => {
      const countries = loadJSONFile<any>('smom_countries.json')
      return countries.find((c: any) => c.name === name) || null
    },

    networkTopologies: async (_, { filter }) => {
      const topologies = loadJSONFile<any>('network_topology.json')
      if (!filter) return topologies

      return topologies.filter((t: any) => {
        if (filter.region && t.region !== filter.region) return false
        if (filter.entity && t.entity !== filter.entity) return false
        return true
      })
    },

    networkTopology: async (_, { id }) => {
      const topologies = loadJSONFile<any>('network_topology.json')
      return topologies.find((t: any) => t.id === id) || null
    },

    complianceRequirements: async (_, { filter }) => {
      const requirements = loadJSONFile<any>('compliance_requirements.json')
      if (!filter) return requirements

      return requirements.filter((r: any) => {
        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
      })
    },

    complianceRequirement: async (_, { country }) => {
      const requirements = loadJSONFile<any>('compliance_requirements.json')
      return requirements.find((r: any) => r.country === country) || null
    },

    deploymentMilestones: async (_, { filter }) => {
      const milestones = loadJSONFile<any>('deployment_timeline.json')
      if (!filter) return milestones

      return milestones.filter((m: any) => {
        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
      })
    },

    deploymentMilestone: async (_, { id }) => {
      const milestones = loadJSONFile<any>('deployment_timeline.json')
      return milestones.find((m: any) => m.id === id) || null
    },

    costEstimates: async (_, { filter }) => {
      const estimates = loadJSONFile<any>('cost_estimates.json')
      if (!filter) return estimates

      return estimates.filter((e: any) => {
        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
      })
    },

    costEstimate: async (_, { region, entity, category }) => {
      const estimates = loadJSONFile<any>('cost_estimates.json')
      return estimates.find((e: any) => 
        e.region === region && e.entity === entity && e.category === category
      ) || null
    },

    infrastructureSummary: async () => {
      const countries = loadJSONFile<any>('smom_countries.json')
      const milestones = loadJSONFile<any>('deployment_timeline.json')
      const estimates = loadJSONFile<any>('cost_estimates.json')

      const regions = new Set(countries.map((c: any) => c.region))
      const totalCost = estimates.reduce((sum: number, e: any) => sum + e.annual, 0)

      const progress = milestones.reduce((acc: any, m: any) => {
        acc[m.status] = (acc[m.status] || 0) + 1
        return acc
      }, {})

      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,
        },
      }
    },
  },

  Mutation: {
    updateNetworkTopology: async (_, { id, input }) => {
      const topologies = loadJSONFile<any>('network_topology.json')
      const index = topologies.findIndex((t: any) => t.id === id)
      if (index === -1) {
        throw new Error(`Topology with id ${id} not found`)
      }

      const updated = {
        ...topologies[index],
        ...input,
        lastUpdated: new Date().toISOString(),
      }

      topologies[index] = updated
      fs.writeFileSync(
        path.join(DATA_DIR, 'network_topology.json'),
        JSON.stringify(topologies, null, 2)
      )

      return updated
    },

    createDeploymentMilestone: async (_, { input }) => {
      const milestones = loadJSONFile<any>('deployment_timeline.json')
      const newMilestone = {
        id: `milestone-${Date.now()}`,
        ...input,
      }

      milestones.push(newMilestone)
      fs.writeFileSync(
        path.join(DATA_DIR, 'deployment_timeline.json'),
        JSON.stringify(milestones, null, 2)
      )

      return newMilestone
    },

    updateDeploymentMilestone: async (_, { id, input }) => {
      const milestones = loadJSONFile<any>('deployment_timeline.json')
      const index = milestones.findIndex((m: any) => m.id === id)
      if (index === -1) {
        throw new Error(`Milestone with id ${id} not found`)
      }

      const updated = {
        ...milestones[index],
        ...input,
      }

      milestones[index] = updated
      fs.writeFileSync(
        path.join(DATA_DIR, 'deployment_timeline.json'),
        JSON.stringify(milestones, null, 2)
      )

      return updated
    },

    deleteDeploymentMilestone: async (_, { id }) => {
      const milestones = loadJSONFile<any>('deployment_timeline.json')
      const filtered = milestones.filter((m: any) => m.id !== id)
      
      fs.writeFileSync(
        path.join(DATA_DIR, 'deployment_timeline.json'),
        JSON.stringify(filtered, null, 2)
      )

      return true
    },

    updateComplianceRequirement: async (_, { country, input }) => {
      const requirements = loadJSONFile<any>('compliance_requirements.json')
      const index = requirements.findIndex((r: any) => r.country === country)
      
      if (index === -1) {
        throw new Error(`Compliance requirement for ${country} not found`)
      }

      const updated = {
        ...requirements[index],
        ...input,
      }

      requirements[index] = updated
      fs.writeFileSync(
        path.join(DATA_DIR, 'compliance_requirements.json'),
        JSON.stringify(requirements, null, 2)
      )

      return updated
    },

    updateCostEstimate: async (_, { region, entity, category, input }) => {
      const estimates = loadJSONFile<any>('cost_estimates.json')
      const index = estimates.findIndex((e: any) => 
        e.region === region && e.entity === entity && e.category === category
      )

      if (index === -1) {
        throw new Error(`Cost estimate not found`)
      }

      const updated = {
        ...estimates[index],
        ...input,
        lastUpdated: new Date().toISOString(),
      }

      estimates[index] = updated
      fs.writeFileSync(
        path.join(DATA_DIR, 'cost_estimates.json'),
        JSON.stringify(estimates, null, 2)
      )

      return updated
    },
  },
}

