#!/usr/bin/env node
import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs'
import { deserialize, serialize } from 'node:v8'
import { WaHttpRegistrationFlow } from '../src/auth/registration/WaHttpRegistrationFlow'
import { parseAndroidApkMaterial } from '../src/auth/registration/token'
import { ConsoleLogger } from '../src/infra/log/ConsoleLogger'
import type { LogLevel } from '../src/infra/log/types'
import type { WaAuthCredentials } from '../src/auth/types'
import type { WaAuthStore } from '../src/store/contracts/auth.store'
import { WaPreKeyMemoryStore } from '../src/store/memory/pre-key.store'
import { WaSignalMemoryStore } from '../src/store/memory/signal.store'

class FileAuthStore implements WaAuthStore {
    private credentials: WaAuthCredentials | null = null
    private readonly path: string

    constructor(path: string) {
        this.path = path
        if (existsSync(path)) {
            this.credentials = deserialize(readFileSync(path)) as WaAuthCredentials
        }
    }

    async load(): Promise<WaAuthCredentials | null> {
        return this.credentials
    }

    async save(credentials: WaAuthCredentials): Promise<void> {
        this.credentials = credentials
        writeFileSync(this.path, serialize(credentials), { mode: 0o600 })
        chmodSync(this.path, 0o600)
    }

    async clear(): Promise<void> {
        this.credentials = null
    }
}

function resolveLogLevel(value: string | undefined): LogLevel {
    switch (value) {
        case 'trace':
        case 'debug':
        case 'info':
        case 'warn':
        case 'error':
            return value
        default:
            return 'info'
    }
}

async function main() {
    const logger = new ConsoleLogger(resolveLogLevel(process.env.LOG_LEVEL))
    const statePath = process.env.WA_STATE_FILE || '/mnt/marlonivo.com/home/ivo/ongoing/code/zapo/registration-state.bin'
    const authStore = new FileAuthStore(statePath)
    const signalStore = new WaSignalMemoryStore()
    const preKeyStore = new WaPreKeyMemoryStore()

    const materialPath = process.env.WA_ANDROID_APK_MATERIAL
    const androidApkMaterial = materialPath
        ? parseAndroidApkMaterial(JSON.parse(readFileSync(materialPath, 'utf8')))
        : undefined

    const flow = new WaHttpRegistrationFlow({
        logger,
        authStore,
        signalStore,
        preKeyStore,
        androidApkMaterial,
        baseUrl: process.env.WA_REGISTRATION_BASE_URL || undefined
    })

    await flow.loadOrCreateKeys()
    console.log('Keys loaded/created, state:', statePath)

    const cc = process.env.CC || ''
    const inNum = process.env.NUMBER || ''
    if (!cc || !inNum) {
        console.error('Set CC and NUMBER env vars')
        process.exit(1)
    }

    const registrationOs = process.env.WA_REGISTRATION_OS === 'ios' ? 'ios' : 'android'
    if (registrationOs === 'android' && !androidApkMaterial) {
        console.error('Android registration needs WA_ANDROID_APK_MATERIAL')
        process.exit(1)
    }
    const deviceInfo = registrationOs === 'ios' ? { os: 'ios' as const } : undefined
    const method = (process.env.METHOD || 'wa_old') as 'sms' | 'voice' | 'wa_old'

    const codeResult = await flow.requestCode({ cc, in: inNum, method, deviceInfo })
    console.log('Code result:', JSON.stringify(codeResult))

    if (codeResult.status !== 'sent') {
        process.exit(2)
    }

    const readline = await import('node:readline')
    const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
    const code = await new Promise<string>((resolve) => {
        rl.question('Enter code: ', (ans) => {
            rl.close()
            resolve(ans.trim())
        })
    })

    const reg = await flow.registerPhone({ cc, in: inNum, method, code, deviceInfo })
    console.log('Registered:', reg.meJid)
    console.log('State saved:', statePath)
}

main().catch((e) => {
    console.error(e)
    process.exit(1)
})
