import fs from 'fs'
import path from 'path'
import { app } from 'electron'

export class ConfigService {
    private configDir: string
    private templateDir: string
    private settingsPath: string
    private defaultSettings = {
        nginxPort: '80',
        apachePort: '8080',
        serverType: 'nginx' as 'nginx' | 'apache',
        phpPort: '9001',
        mariaDbPort: '3306',
        mariaDbPorts: {} as Record<string, string>,
        allowRemoteAccess: false,
        language: 'tr'
    }

    constructor() {
        this.templateDir = path.join(app.getAppPath(), 'config')
        const base = this.getBasePath()
        this.configDir = path.join(base, 'generated_configs')
        this.settingsPath = path.join(base, 'settings.json')

        if (!fs.existsSync(this.configDir)) {
            fs.mkdirSync(this.configDir, { recursive: true })
        }

        if (!fs.existsSync(this.settingsPath)) {
            fs.writeFileSync(this.settingsPath, JSON.stringify(this.defaultSettings, null, 2))
        }
    }

    getBasePath(): string {
        if (app.isPackaged) {
            return path.dirname(app.getPath('exe'))
        }
        return process.cwd()
    }

    async generateConfig(templateName: string, targetName: string, variables: Record<string, string>): Promise<string> {
        const templatePath = path.join(this.templateDir, templateName)
        const targetPath = path.join(this.configDir, targetName)

        if (!fs.existsSync(templatePath)) {
            throw new Error(`Template not found: ${templatePath}`)
        }

        let content = fs.readFileSync(templatePath, 'utf-8')

        for (const [key, value] of Object.entries(variables)) {
            const escapedValue = value.replace(/\\/g, '/') // Use forward slashes for cross-platform compatibility in configs
            content = content.replace(new RegExp(`{{${key}}}`, 'g'), escapedValue)
        }

        fs.writeFileSync(targetPath, content)
        return targetPath
    }

    getGeneratedPath(targetName: string): string {
        return path.join(this.configDir, targetName)
    }

    getSettings(): any {
        try {
            if (fs.existsSync(this.settingsPath)) {
                const data = fs.readFileSync(this.settingsPath, 'utf-8')
                return { ...this.defaultSettings, ...JSON.parse(data) }
            }
        } catch (e) {
            console.error('Failed to read settings:', e)
        }
        return this.defaultSettings
    }

    updateSettings(newSettings: any) {
        try {
            const current = this.getSettings()
            const updated = { ...current, ...newSettings }
            fs.writeFileSync(this.settingsPath, JSON.stringify(updated, null, 2))
            return updated
        } catch (e) {
            console.error('Failed to save settings:', e)
            throw e
        }
    }
}

export const configService = new ConfigService()
