import { exec } from 'child_process'
import { promisify } from 'util'

const execAsync = promisify(exec)

export interface OSOperations {
    addHostEntry(ip: string, host: string): Promise<boolean>
    isElevated(): Promise<boolean>
    runElevated(command: string): Promise<{ stdout: string, stderr: string }>
}

export class WindowsOperations implements OSOperations {
    async addHostEntry(ip: string, host: string): Promise<boolean> {
        const entry = `${ip} ${host}`
        const hostsPath = 'C:\\Windows\\System32\\drivers\\etc\\hosts'
        try {
            // Use powershell to append to hosts file if not exists
            const command = `powershell -Command "if (!(Get-Content ${hostsPath} | Select-String '${host}')) { Add-Content ${hostsPath} '${entry}' }"`
            await this.runElevated(command)
            return true
        } catch (error) {
            console.error('Failed to add host entry:', error)
            return false
        }
    }

    async isElevated(): Promise<boolean> {
        try {
            await execAsync('net session')
            return true
        } catch {
            return false
        }
    }

    async runElevated(command: string): Promise<{ stdout: string, stderr: string }> {
        // In a real app, we would use sudo-prompt or a similar library.
        // For now, we assume the app might be run as admin or we use a basic exec.
        return execAsync(command)
    }
}

export const osOps: OSOperations = new WindowsOperations()
