// bot/src/versioning.ts — Tracks release versions per card
// Stored in .sdd/bot/versions/<cardId>.json: { version: number }
// Version format: "0.0.<n>"

import fs from 'node:fs'
import path from 'node:path'

interface VersionFile {
  version: number
}

export class VersionTracker {
  private static instances = new Map<string, VersionTracker>()

  private readonly filePath: string
  private versionNumber: number

  private constructor(cardId: string, botDir: string) {
    const versionsDir = path.join(botDir, '.sdd', 'bot', 'versions')
    fs.mkdirSync(versionsDir, { recursive: true })
    this.filePath = path.join(versionsDir, `${cardId}.json`)

    if (fs.existsSync(this.filePath)) {
      const raw = fs.readFileSync(this.filePath, 'utf-8')
      const data = JSON.parse(raw) as VersionFile
      this.versionNumber = data.version
    } else {
      this.versionNumber = 0
      this.persist()
    }
  }

  static getInstance(cardId: string, botDir: string): VersionTracker {
    const key = `${botDir}::${cardId}`
    let instance = VersionTracker.instances.get(key)
    if (!instance) {
      instance = new VersionTracker(cardId, botDir)
      VersionTracker.instances.set(key, instance)
    }
    return instance
  }

  // Increments version and returns new version string (e.g. "0.0.3")
  getNext(): string {
    this.versionNumber += 1
    this.persist()
    return this.format()
  }

  // Returns current version without incrementing
  current(): string {
    return this.format()
  }

  private format(): string {
    return `0.0.${this.versionNumber}`
  }

  private persist(): void {
    const data: VersionFile = { version: this.versionNumber }
    fs.writeFileSync(this.filePath, JSON.stringify(data, null, 2), 'utf-8')
  }
}
