import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

interface TLSDependencyPath {
    DOWNLOAD_PATH: string;
    TLS_LIB_PATH: string;
}

class TlsDependency {
    private readonly arch: string;
    private readonly platform: NodeJS.Platform;
    private readonly version: string;
    private readonly filename: string;
    private extension: string;
    private distribution: string;

    constructor() {
        this.arch = os.arch();
        this.platform = os.platform();
        this.version = '1.15.1';
        this.filename = 'tls-client-xgo';
        this.extension = '';
        this.distribution = '';
        this.setDetails();
    }

    private setDetails(): void {
        if (this.platform === 'win32') {
            this.extension = 'dll';
            this.distribution = this.arch.includes('64') ? 'windows-amd64' : 'windows-386';
        } else if (this.platform === 'darwin') {
            this.extension = 'dylib';
            this.distribution = this.arch === 'arm64' ? 'darwin-arm64' : 'darwin-amd64';
        } else if (this.platform === 'linux') {
            this.extension = 'so';

            const archMap: Record<string, string> = {
                arm64: 'linux-arm64',
                x64: 'linux-amd64',
                ia32: 'linux-386',
                arm: 'linux-arm-7', // assuming ARMv7
                ppc64: 'linux-ppc64le',
                riscv64: 'linux-riscv64',
                s390x: 'linux-s390x',
            };

            const distribution = archMap[this.arch];

            if (!distribution) {
                console.error(`Unsupported architecture: ${this.arch}, defaulting to linux-amd64`);
            }

            this.distribution = distribution ?? 'linux-amd64';
        } else {
            throw new Error(`Unsupported platform: ${this.platform}`);
        }
    }

    getTLSDependencyPath(customPath?: string | null): TLSDependencyPath {
        const filename = `${this.filename}-${this.version}-${this.distribution}.${this.extension}`;
        const downloadFolder = customPath ?? os.tmpdir();

        if (!fs.existsSync(downloadFolder)) {
            throw new Error(`The download folder does not exist: ${downloadFolder}`);
        }

        return {
            DOWNLOAD_PATH: `https://github.com/bogdanfinn/tls-client/releases/download/v${this.version}/${filename}`,
            TLS_LIB_PATH: path.join(downloadFolder, filename),
        };
    }
}

export default TlsDependency;
