const express = require('express')
const fs = require('fs')
const path = require('path')
const router = express.Router()
const { weaponsHelpers, logToFile } = require('../mariadb')

const ARMOURY_PATH = path.join(__dirname, '..', '..', 'public', 'deathwatch-armoury.json')

function cardCategory(category) {
  if (category === 'Melee Weapon' || category === 'Ranged Weapon' || category === 'Grenade') return category
  if (/armou?r|shield/i.test(category || '')) return 'Armour'
  return 'Other'
}

function protectionText(protection) {
  if (!protection || typeof protection !== 'object') return ''
  return Object.entries(protection)
    .map(([loc, value]) => `${loc}: ${value}`)
    .join('; ')
}

function loadArmouryFallback() {
  const raw = JSON.parse(fs.readFileSync(ARMOURY_PATH, 'utf8'))
  const groups = raw.items || {}
  let id = 1
  return Object.values(groups).flatMap(items => {
    if (!Array.isArray(items)) return []
    return items.map(item => {
      const stats = { ...(item.stats || {}) }
      if (item.req != null) stats.req = item.req
      if (item.renown != null) stats.renown = item.renown
      if (!stats.damage && stats.protection) stats.damage = protectionText(stats.protection)
      return {
        id: `armoury-${id++}`,
        name: item.name,
        category: cardCategory(item.category),
        stats,
        source: stats.source || item.source || 'deathwatch-armoury.json'
      }
    }).filter(item => item.name)
  })
}

// Return weapons in a normalized shape
router.get('/', async (req, res) => {
  try {
    const rows = await weaponsHelpers.getAll()
    const parsed = rows.map(r => {
      let stats = {}
      try { 
        stats = typeof r.stats === 'string' ? JSON.parse(r.stats) : r.stats || {}
      } catch (e) {
        logToFile('Error parsing weapon stats for', r.name, e)
      }
      return { id: r.id, name: r.name, category: r.category, stats: stats, source: r.source }
    })
    res.json(parsed.length ? parsed : loadArmouryFallback())
  } catch (e) {
    console.error('Failed to load weapons from MariaDB:', e)
    logToFile('Error getting weapons:', e)
    try {
      res.json(loadArmouryFallback())
    } catch (fallbackError) {
      logToFile('Error loading armoury fallback:', fallbackError)
      res.status(500).json({ error: 'Failed to get weapons' })
    }
  }
})

module.exports = router
