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

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

export class ApacheManagerService {
    private versions: ApacheVersion[] = []
    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<ApacheVersion[]> {
        // Apache Lounge VS17 Win64 version
        const stableVersion = '2.4.66'
        const url = `https://www.apachelounge.com/download/VS18/binaries/httpd-2.4.66-260223-Win64-VS18.zip`

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

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

        const v: ApacheVersion = {
            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 findHttpd = (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 (findHttpd(p)) return true
                } else if (f.toLowerCase() === 'httpd.exe') {
                    return true
                }
            }
            return false
        }

        return findHttpd(dir)
    }

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

export const apacheManagerService = new ApacheManagerService()
