import fs from 'fs'
import path from 'path'
import { configService } from './ConfigService'

interface PortMap {
    php: Record<string, number>;
    mysql: Record<string, number>;
}

export class PortMappingService {
    private configFile: string
    private portMap: PortMap = { php: {}, mysql: {} }
    private nextPhpPort = 9001
    private nextMysqlPort = 3306

    constructor() {
        this.configFile = path.join(configService.getBasePath(), 'port_mappings.json')
        this.load()
    }

    private load() {
        if (fs.existsSync(this.configFile)) {
            try {
                this.portMap = JSON.parse(fs.readFileSync(this.configFile, 'utf-8'))

                const phpPorts = Object.values(this.portMap.php)
                if (phpPorts.length > 0) this.nextPhpPort = Math.max(...phpPorts) + 1

                const mysqlPorts = Object.values(this.portMap.mysql)
                if (mysqlPorts.length > 0) this.nextMysqlPort = Math.max(...mysqlPorts) + 1
            } catch (e) {
                console.error('Failed to load port mappings', e)
            }
        }
    }

    private save() {
        fs.writeFileSync(this.configFile, JSON.stringify(this.portMap, null, 2))
    }

    getPhpPort(version: string): number {
        if (!this.portMap.php[version]) {
            this.portMap.php[version] = this.nextPhpPort++
            this.save()
        }
        return this.portMap.php[version]
    }

    getMySqlPort(version: string): number {
        if (!this.portMap.mysql[version]) {
            this.portMap.mysql[version] = this.nextMysqlPort++
            this.save()
        }
        return this.portMap.mysql[version]
    }
}

export const portMappingService = new PortMappingService()
