import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'
import { createInitialState } from './gameState.js'

const STATE_PATH = join(dirname(fileURLToPath(import.meta.url)), '..', '.segnapunti', 'state.json')

export function loadState() {
    try {
        if (existsSync(STATE_PATH)) {
            return JSON.parse(readFileSync(STATE_PATH, 'utf8'))
        }
    } catch (err) {
        console.warn('[Persist] Stato non leggibile, si riparte da zero:', err.message)
    }
    return createInitialState()
}

export function saveState(state) {
    try {
        mkdirSync(dirname(STATE_PATH), { recursive: true })
        writeFileSync(STATE_PATH, JSON.stringify(state), 'utf8')
    } catch (err) {
        console.error('[Persist] Salvataggio fallito:', err.message)
    }
}
