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

export interface NginxVersion {
    id: string
    version: string
    url: string
    status: 'available' | 'downloading' | 'installed'
    progress: number
}

export class NginxManagerService {
    private versions: NginxVersion[] = []
    private binDir: string

    constructor() {
        this.binDir = path.join(configService.getBasePath(), 'bin')
        this.init()
    }

    private async init() {
        if (!fs.existsSync(this.binDir)) {
            fs.mkdirSync(this.binDir, { recursive: true })
        }
    }

    async getVersions(): Promise<NginxVersion[]> {
        // For Nginx, we can stick to one stable version or a small list
        const stableVersion = '1.26.2'
        const url = `https://nginx.org/download/nginx-${stableVersion}.zip`

        const id = 'nginx'
        const targetDir = path.join(this.binDir, id)

        // Check if installed (look for nginx.exe anywhere in the zip extraction folder)
        const isInstalled = this.isInstalled(targetDir)

        const v: NginxVersion = {
            id,
            version: stableVersion,
            url,
            status: isInstalled ? 'installed' : 'available',
            progress: isInstalled ? 100 : 0
        }

        // Maintain internal state for progress updates
        const existing = this.versions.find(ev => ev.id === id)
        if (existing && existing.status === 'downloading') {
            return [existing]
        }

        this.versions = [v]
        return this.versions
    }

    private isInstalled(dir: string): boolean {
        if (!fs.existsSync(dir)) return false

        const findNginx = (d: string): boolean => {
            const files = fs.readdirSync(d)
            for (const f of files) {
                const p = path.join(d, f)
                const s = fs.statSync(p)
                if (s.isDirectory()) {
                    if (findNginx(p)) return true
                } else if (f.toLowerCase() === 'nginx.exe') {
                    return true
                }
            }
            return false
        }

        return findNginx(dir)
    }

    updateProgress(id: string, progress: number, status: NginxVersion['status'] = 'downloading') {
        const v = this.versions.find(ev => ev.id === id)
        if (v) {
            v.progress = progress
            v.status = status
        }
    }
}

export const nginxManagerService = new NginxManagerService()
