#!/usr/bin/env node

import { promises as fs } from 'node:fs'
import path from 'node:path'
import {
  convertImportedSpielplanToJson,
  validateImportedSpielplan
} from '../server/utils/spielplan-data.js'

const DEFAULT_INPUT = 'server/data/spielplan-import/harheimer_tc_spielplan.json'
const PUBLIC_SEASONS_DIR = 'public/data/spielplaene'
const INTERNAL_SEASONS_DIR = 'server/data/public-data/spielplaene'

function getArgValue(name) {
  const index = process.argv.indexOf(name)
  return index >= 0 ? process.argv[index + 1] : null
}

async function writeJsonAtomic(filePath, data) {
  await fs.mkdir(path.dirname(filePath), { recursive: true })
  const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`
  const content = `${JSON.stringify(data, null, 2)}\n`

  await fs.writeFile(tmpPath, content, 'utf8')
  await fs.rename(tmpPath, filePath)
}

const inputPath = getArgValue('--input') || DEFAULT_INPUT
const publicSeasonsDir = getArgValue('--output-dir') || PUBLIC_SEASONS_DIR
const raw = await fs.readFile(inputPath, 'utf8')
const imported = JSON.parse(raw)

validateImportedSpielplan(imported)

const spielplan = convertImportedSpielplanToJson(imported)
const seasonSlug = imported.source?.season?.seasonSlug
if (!seasonSlug) {
  throw new Error('Saison-Slug fehlt in der Import-Datei')
}

const publicSeasonPath = path.join(publicSeasonsDir, `spielplan-${seasonSlug}.json`)
const internalSeasonPath = path.join(INTERNAL_SEASONS_DIR, `spielplan-${seasonSlug}.json`)

await writeJsonAtomic(publicSeasonPath, spielplan)
await writeJsonAtomic(internalSeasonPath, spielplan)

console.log(`Validiert: ${imported.matchCount} Spiele, Saison ${seasonSlug}`)
console.log(`Saison-Datei: ${publicSeasonPath}`)
console.log(`Interne Saison-Datei: ${internalSeasonPath}`)
