import {InfisicalSDK} from "@infisical/sdk"

const client = new InfisicalSDK({
    siteUrl: "https://secrets.fedeo.io"
})



export let secrets = {

} as {
    COOKIE_SECRET: string
    JWT_SECRET: string
    PORT: number
    HOST: string
    DATABASE_URL: string
    S3_BUCKET: string
    ENCRYPTION_KEY: string
    MAILER_SMTP_HOST: string
    MAILER_SMTP_PORT: number
    MAILER_SMTP_SSL: string
    MAILER_SMTP_USER: string
    MAILER_SMTP_PASS: string
    MAILER_FROM: string
    S3_ENDPOINT: string
    S3_REGION: string
    S3_ACCESS_KEY: string
    S3_SECRET_KEY: string
    M2M_API_KEY: string
    API_BASE_URL: string
    GOCARDLESS_BASE_URL: string
    GOCARDLESS_SECRET_ID: string
    GOCARDLESS_SECRET_KEY: string
    DOKUBOX_IMAP_HOST: string
    DOKUBOX_IMAP_PORT: number
    DOKUBOX_IMAP_SECURE: boolean
    DOKUBOX_IMAP_USER: string
    DOKUBOX_IMAP_PASSWORD: string
    OPENAI_API_KEY: string
    STIRLING_API_KEY: string
    MATRIX_HOMESERVER_URL?: string
    MATRIX_SERVER_NAME?: string
    MATRIX_RTC_HOST?: string
    MATRIX_RTC_JWT_URL?: string
    MATRIX_LIVEKIT_URL?: string
    MATRIX_REGISTRATION_SHARED_SECRET?: string
    MATRIX_SERVICE_USER_LOCALPART?: string
    LIVEKIT_KEY?: string
    LIVEKIT_SECRET?: string
    WEB_PUSH_PUBLIC_KEY?: string
    WEB_PUSH_PRIVATE_KEY?: string
    WEB_PUSH_SUBJECT?: string
    PUSH_SERVER_URL?: string
    PUSH_SERVER_INSTANCE_ID?: string
    PUSH_SERVER_SECRET?: string
}

const secretKeys = [
    "COOKIE_SECRET",
    "JWT_SECRET",
    "PORT",
    "HOST",
    "DATABASE_URL",
    "S3_BUCKET",
    "ENCRYPTION_KEY",
    "MAILER_SMTP_HOST",
    "MAILER_SMTP_PORT",
    "MAILER_SMTP_SSL",
    "MAILER_SMTP_USER",
    "MAILER_SMTP_PASS",
    "MAILER_FROM",
    "S3_ENDPOINT",
    "S3_REGION",
    "S3_ACCESS_KEY",
    "S3_SECRET_KEY",
    "M2M_API_KEY",
    "API_BASE_URL",
    "GOCARDLESS_BASE_URL",
    "GOCARDLESS_SECRET_ID",
    "GOCARDLESS_SECRET_KEY",
    "DOKUBOX_IMAP_HOST",
    "DOKUBOX_IMAP_PORT",
    "DOKUBOX_IMAP_SECURE",
    "DOKUBOX_IMAP_USER",
    "DOKUBOX_IMAP_PASSWORD",
    "OPENAI_API_KEY",
    "STIRLING_API_KEY",
    "MATRIX_HOMESERVER_URL",
    "MATRIX_SERVER_NAME",
    "MATRIX_RTC_HOST",
    "MATRIX_RTC_JWT_URL",
    "MATRIX_LIVEKIT_URL",
    "MATRIX_REGISTRATION_SHARED_SECRET",
    "MATRIX_SERVICE_USER_LOCALPART",
    "LIVEKIT_KEY",
    "LIVEKIT_SECRET",
    "WEB_PUSH_PUBLIC_KEY",
    "WEB_PUSH_PRIVATE_KEY",
    "WEB_PUSH_SUBJECT",
    "PUSH_SERVER_URL",
    "PUSH_SERVER_INSTANCE_ID",
    "PUSH_SERVER_SECRET",
] as const

const numberKeys = new Set(["PORT", "MAILER_SMTP_PORT", "DOKUBOX_IMAP_PORT"])
const booleanKeys = new Set(["DOKUBOX_IMAP_SECURE"])

function normalizeEnvValue(key: string, value: string) {
    if (numberKeys.has(key)) return Number(value)
    if (booleanKeys.has(key)) return value === "true"
    return value
}

function loadSecretsFromEnv() {
    let loaded = 0

    secretKeys.forEach((key) => {
        const value = process.env[key]
        if (value === undefined || value === "") return

        ;(secrets as Record<string, any>)[key] = normalizeEnvValue(key, value)
        loaded++
    })

    if (!secrets.HOST) secrets.HOST = "0.0.0.0"
    if (!secrets.PORT) secrets.PORT = 3100

    return loaded
}

export async function loadSecrets () {
    const envSecretCount = loadSecretsFromEnv()

    if (!process.env.INFISICAL_CLIENT_ID || !process.env.INFISICAL_CLIENT_SECRET) {
        console.log(`✅ Secrets aus Umgebungsvariablen geladen (${envSecretCount} Stück)`)
        return
    }

    await client.auth().universalAuth.login({
        clientId: process.env.INFISICAL_CLIENT_ID,
        clientSecret: process.env.INFISICAL_CLIENT_SECRET,
    });

    const allSecrets = await client.secrets().listSecrets({
        environment: "dev", // stg, dev, prod, or custom environment slugs
        projectId: "39774094-2aaf-49fb-a213-d6b2c10f6144"
    });

    allSecrets.secrets.forEach(secret => {
        ;(secrets as Record<string, any>)[secret.secretKey] = normalizeEnvValue(secret.secretKey, secret.secretValue)
    })
    loadSecretsFromEnv()
    console.log("✅ Secrets aus Infisical und Umgebungsvariablen geladen");
    console.log(Object.keys(secrets).length + " Stück")
}
