import fs from 'fs'
import { phpManagerService } from './PhpManagerService'
import { mariaDbManagerService } from './MariaDbManagerService'
import { configService } from './ConfigService'

export class CliAliasService {
    async generateAliases() {
        const phpVersions = await phpManagerService.getVersions()
        const mariaDbVersions = await mariaDbManagerService.getVersions()

        const installedPhp = phpVersions.filter(v => v.status === 'installed')
        const installedMariaDb = mariaDbVersions.filter(v => v.status === 'installed')

        await this.generatePowerShellAliases(installedPhp, installedMariaDb)
        await this.generateBashAliases(installedPhp, installedMariaDb)
    }

    private async generatePowerShellAliases(phpVersions: any[], mariaDbVersions: any[]) {
        let content = '# MultiPHP PowerShell Aliases\n\n'

        // PHP Aliases
        for (const v of phpVersions) {
            const binaryPath = await phpManagerService.getPhpBinaryPath(v.version)
            if (binaryPath) {
                const shortVersion = v.version.split('.').slice(0, 2).join('') // 7.4 -> 74
                const majorVersion = v.version.split('.')[0] // 8.1 -> 8

                content += `function php${v.version.replace(/\./g, '')} { & "${binaryPath}" @args }\n`
                content += `function php${shortVersion} { & "${binaryPath}" @args }\n`

                // If it's the latest of its major version (they are sorted descending)
                const isLatestMajor = phpVersions.find(pv => pv.version.startsWith(majorVersion)) === v
                if (isLatestMajor) {
                    content += `function php${majorVersion} { & "${binaryPath}" @args }\n`
                }
            }
        }

        // Global php (latest installed)
        if (phpVersions.length > 0) {
            const latestPhp = phpVersions[0]
            const latestPath = await phpManagerService.getPhpBinaryPath(latestPhp.version)
            if (latestPath) {
                content += `function php { & "${latestPath}" @args }\n`
            }
        }

        // MariaDB/MySQL Aliases
        for (const v of mariaDbVersions) {
            const binaryPath = await mariaDbManagerService.getMariaDbBinaryPath(v.version)
            if (binaryPath) {
                const shortVersion = v.version.split('.').slice(0, 2).join('') // 10.11 -> 1011
                content += `function mysql${shortVersion} { & "${binaryPath}" @args }\n`
                content += `function mariadb${shortVersion} { & "${binaryPath}" @args }\n`
            }
        }

        // Global mysql/mariadb (latest installed)
        if (mariaDbVersions.length > 0) {
            const latestDb = mariaDbVersions[0]
            const latestPath = await mariaDbManagerService.getMariaDbBinaryPath(latestDb.version)
            if (latestPath) {
                content += `function mysql { & "${latestPath}" @args }\n`
                content += `function mariadb { & "${latestPath}" @args }\n`
            }
        }

        const targetPath = configService.getGeneratedPath('aliases.ps1')
        fs.writeFileSync(targetPath, content)
    }

    private async generateBashAliases(phpVersions: any[], mariaDbVersions: any[]) {
        let content = '# MultiPHP Bash/Zsh Aliases\n\n'

        // PHP Aliases
        for (const v of phpVersions) {
            const binaryPath = await phpManagerService.getPhpBinaryPath(v.version)
            if (binaryPath) {
                const normalizedPath = binaryPath.replace(/\\/g, '/')
                const shortVersion = v.version.split('.').slice(0, 2).join('')
                const majorVersion = v.version.split('.')[0]

                content += `alias php${v.version.replace(/\./g, '')}='${normalizedPath}'\n`
                content += `alias php${shortVersion}='${normalizedPath}'\n`

                const isLatestMajor = phpVersions.find(pv => pv.version.startsWith(majorVersion)) === v
                if (isLatestMajor) {
                    content += `alias php${majorVersion}='${normalizedPath}'\n`
                }
            }
        }

        if (phpVersions.length > 0) {
            const latestPhp = phpVersions[0]
            const latestPath = (await phpManagerService.getPhpBinaryPath(latestPhp.version))?.replace(/\\/g, '/')
            if (latestPath) {
                content += `alias php='${latestPath}'\n`
            }
        }

        // MariaDB Aliases
        for (const v of mariaDbVersions) {
            const binaryPath = await mariaDbManagerService.getMariaDbBinaryPath(v.version)
            if (binaryPath) {
                const normalizedPath = binaryPath.replace(/\\/g, '/')
                const shortVersion = v.version.split('.').slice(0, 2).join('')
                content += `alias mysql${shortVersion}='${normalizedPath}'\n`
                content += `alias mariadb${shortVersion}='${normalizedPath}'\n`
            }
        }

        if (mariaDbVersions.length > 0) {
            const latestDb = mariaDbVersions[0]
            const latestPath = (await mariaDbManagerService.getMariaDbBinaryPath(latestDb.version))?.replace(/\\/g, '/')
            if (latestPath) {
                content += `alias mysql='${latestPath}'\n`
                content += `alias mariadb='${latestPath}'\n`
            }
        }

        const targetPath = configService.getGeneratedPath('aliases.sh')
        fs.writeFileSync(targetPath, content)
    }
}

export const cliAliasService = new CliAliasService()
