#!/usr/bin/env node
const path = require('path')
const fs = require('fs')

const operation = process.argv[2]
const relativePath = process.argv[3]
const jsonString = process.argv[4]
const keyPathJson = process.argv[5]

if (!operation || !relativePath) {
  process.stdout.write(JSON.stringify({
    success: false,
    error: 'Missing required parameters: operation and filePath'
  }) + '\n')
  process.exit(1)
}

const staticDir = path.resolve(__dirname, '..', 'static')
const normalizedPath = path.normalize(relativePath).replace(/\\/g, '/')
if (normalizedPath.includes('..') || normalizedPath.startsWith('/')) {
  process.stdout.write(JSON.stringify({
    success: false,
    error: 'Invalid file path'
  }) + '\n')
  process.exit(1)
}

const fileName = normalizedPath.endsWith('.json') ? normalizedPath : `${normalizedPath}.json`
const filePath = path.resolve(staticDir, fileName)

if (!filePath.startsWith(staticDir)) {
  process.stdout.write(JSON.stringify({
    success: false,
    error: 'File path must be within static directory'
  }) + '\n')
  process.exit(1)
}

function getNestedValue(obj, keyPath) {
  let current = obj
  for (const key of keyPath) {
    if (current === null || current === undefined) return undefined
    current = current[key]
  }
  return current
}

function setNestedValue(obj, keyPath, value) {
  let current = obj
  for (let i = 0; i < keyPath.length - 1; i++) {
    const key = keyPath[i]
    if (current[key] === null || current[key] === undefined) {
      current[key] = typeof keyPath[i + 1] === 'number' ? [] : {}
    }
    current = current[key]
  }
  current[keyPath[keyPath.length - 1]] = value
}

const dir = path.dirname(filePath)
if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir, { recursive: true })
}

let result

if (operation === 'create') {
  if (!jsonString) {
    result = { success: false, error: 'Missing jsonString parameter for create operation' }
  } else {
    fs.writeFileSync(filePath, JSON.stringify(JSON.parse(jsonString), null, 2), 'utf8')
    result = { success: true, message: 'JSON file created successfully' }
  }
} else if (operation === 'read') {
  if (!fs.existsSync(filePath)) {
    result = { success: false, error: 'JSON file does not exist' }
  } else {
    const jsonData = JSON.parse(fs.readFileSync(filePath, 'utf8'))
    result = {
      success: true,
      data: keyPathJson ? getNestedValue(jsonData, JSON.parse(keyPathJson)) : jsonData
    }
  }
} else if (operation === 'update') {
  if (!fs.existsSync(filePath)) {
    result = { success: false, error: 'JSON file does not exist' }
  } else if (!jsonString) {
    result = { success: false, error: 'Missing jsonString parameter for update operation' }
  } else {
    const jsonData = JSON.parse(fs.readFileSync(filePath, 'utf8'))
    const newValue = JSON.parse(jsonString)
    if (keyPathJson) {
      setNestedValue(jsonData, JSON.parse(keyPathJson), newValue)
    } else {
      Object.assign(jsonData, newValue)
    }
    fs.writeFileSync(filePath, JSON.stringify(jsonData, null, 2), 'utf8')
    result = { success: true, message: 'JSON file updated successfully' }
  }
} else if (operation === 'check') {
  result = {
    success: true,
    exists: fs.existsSync(filePath)
  }
} else {
  result = {
    success: false,
    error: `Unknown operation: ${operation}. Supported: create, read, update, check`
  }
}

process.stdout.write(JSON.stringify(result) + '\n')
process.exit(result.success ? 0 : 1)
