// @ts-nocheck
import { error } from '@sveltejs/kit'
import type { LayoutServerLoad } from './$types'
import { Grain } from '../../../../helpers'
import { readFileSync } from 'node:fs'
import { PROJETS_DIR } from '$env/static/private'

export const load = async ({ params }: Parameters<LayoutServerLoad>[0]) => {
    console.log('LOAD')
    if (params['id'] == 'nouveau') {
        const sim = Grain.newSimulationCommunaute()
        console.log(JSON.stringify(sim))
        return <Grain.GetProjetResp>{
            nom: '',
            id: 'nouveau',
            porteur: '',
            tel: '',
            adresse: '',
            simulation: { ...sim },
            email: 'grain@coturnix.fr',
            prms: [],
            profils: [],
            N: 30,
            expert: false,
        }
    }

    try {
        const result = JSON.parse(
            readFileSync(
                PROJETS_DIR + '/' + fixNom(params.id) + '.json',
                'utf8'
            )
        )
        console.log(result)
        return result
    } catch (err) {
        console.error(err)
        return error(500, `${err}`)
    }
}

function fixNom(nom: string): string {
    return nom.replaceAll('/', '_')
}
