import { createHash, createHmac, pbkdf2Sync } from 'node:crypto'

import { randomBytesAsync } from '../../crypto'
import { md5Bytes } from '../../crypto/core/primitives'
import { base64ToBytes, bytesToBase64, bytesToHex, TEXT_ENCODER } from '../../util/bytes'

/**
 * Static iOS token prefix. The registration token is
 *
 *   md5_hex(staticToken + md5_hex(appVersion) + nationalNumber)
 *
 * The same string has been shipped by every iOS build for years. Android does
 * NOT have a usable static token: it signs the token with material taken from
 * its own APK (see {@link AndroidApkMaterial}).
 */
const IOS_STATIC_TOKEN = '0a1mLfGUIBVrMKF1RdvLI5lkRBvof6vn0fD2QRSM'
const IOS_BUSINESS_STATIC_TOKEN = 'USUDuDYDeQhY4RF2fCSp5m3F6kJ1M2J8wS7bbNA2'

/**
 * PBKDF2 salt used by the Android client. Stable across consumer and business
 * builds and unchanged for many releases.
 */
const ANDROID_SALT = base64ToBytes(
    'PkTwKSZqUfAUyR0rPQ8hYJ0wNsQQ3dW1+3SCnyTXIfEAxxS75FwkDf47wNv/c8pP3p0GXKR6OOQmhyERwx74fw1RYSU10I4r1gyBVDbRJ40pidjM41G1I1oN'
)
const ANDROID_PBKDF2_ITERATIONS = 128
const ANDROID_PBKDF2_KEY_SIZE = 64

/** Byte/string union used by the material JSON, which stores base64. */
export type BytesLike = Uint8Array | string

/**
 * The three pieces of APK material the Android registration token is signed
 * with. They cannot be derived — they have to be read out of a WhatsApp APK.
 */
export interface AndroidApkMaterial {
    /** `com.whatsapp` (consumer) or `com.whatsapp.w4b` (business). */
    readonly packageName?: string
    /** 64-byte PBKDF2 output. base64 when it comes from JSON. */
    readonly secretKey: BytesLike
    /** Raw 16-byte MD5 of `classes.dex`. base64 when it comes from JSON. */
    readonly classesDexMd5: BytesLike
    /** DER bytes of every v1 signing certificate, in APK order. base64 in JSON. */
    readonly certificates: readonly BytesLike[]
    /**
     * Version of the APK the material came from. It must be the version sent in
     * the User-Agent, otherwise the server answers `old_version`.
     */
    readonly apkVersion?: string
}

export interface RegistrationTokenOptions {
    /** Platform that will be announced in the User-Agent. */
    readonly os?: 'android' | 'ios' | string
    /** Business builds use a different iOS static token and their own APK. */
    readonly business?: boolean
    /** Override the static iOS token (newer build than this library knows). */
    readonly staticToken?: string
    /** Required when `os === 'android'`. */
    readonly androidMaterial?: AndroidApkMaterial
}

/**
 * Generate a request token (UUID-like string)
 */
export async function generateRequestToken(): Promise<string> {
    const bytes = await randomBytesAsync(16)
    // Format as UUID v4
    bytes[6] = (bytes[6] & 0x0f) | 0x40
    bytes[8] = (bytes[8] & 0x3f) | 0x80
    const hex = Array.from(bytes)
        .map((b) => b.toString(16).padStart(2, '0'))
        .join('')
    return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`
}

/**
 * Java's phone number handling: digits only, leading zeros dropped (the native
 * client converts the national number to a `long`). The token is computed over
 * this value, WITHOUT the country code.
 */
export function normalizeNationalNumber(phone: string): string {
    const digits = String(phone).replace(/\D+/g, '')
    const trimmed = digits.replace(/^0+/, '')
    if (trimmed.length === 0) {
        throw new Error('registration token needs a non-empty national phone number')
    }
    return trimmed
}

/**
 * Calculate the registration token for the platform that will be announced.
 *
 * - iOS: `md5_hex(staticToken + md5_hex(appVersion) + nationalNumber)`.
 * - Android: HMAC-SHA1 over the APK signing certificates + `md5(classes.dex)` +
 *   the national number, URL-encoded base64.
 *
 * `phone` must be the national number (no country code). Passing `cc + in`
 * produces a well-formed token the server rejects with `bad_token`.
 */
export function calculateRegistrationToken(
    version: string,
    phone: string,
    options: RegistrationTokenOptions = {}
): string {
    const national = normalizeNationalNumber(phone)
    if (options.os === 'android') {
        return calculateAndroidRegistrationToken(national, options)
    }
    const staticToken =
        options.staticToken ??
        (options.business ? IOS_BUSINESS_STATIC_TOKEN : IOS_STATIC_TOKEN)
    return md5Hex(staticToken + md5Hex(version) + national)
}

/**
 * Android token, exactly as the native client signs it:
 *
 *   key   = PBKDF2-HMAC-SHA1(packageName || about_logo.png, ANDROID_SALT, 128, 64)
 *   mac   = HMAC-SHA1(key) over certificates..., MD5(classes.dex), national
 *   token = urlencode(base64(mac))
 */
export function calculateAndroidRegistrationToken(
    phone: string,
    options: Pick<RegistrationTokenOptions, 'androidMaterial'>
): string {
    const material = options.androidMaterial
    if (!material) {
        throw new Error(
            'Android registration needs APK material (secretKey, certificates, classesDexMd5). ' +
                'Extract it from the WhatsApp APK with `wa apk-material`, or register as iOS.'
        )
    }
    const key = asBytes(material.secretKey, 'androidMaterial.secretKey')
    const classesDexMd5 = asBytes(material.classesDexMd5, 'androidMaterial.classesDexMd5')
    if (classesDexMd5.length !== 16) {
        throw new Error(`androidMaterial.classesDexMd5 must be 16 bytes, got ${classesDexMd5.length}`)
    }
    const mac = createHmac('sha1', key)
    for (const certificate of material.certificates) {
        mac.update(asBytes(certificate, 'androidMaterial.certificates[]'))
    }
    mac.update(classesDexMd5)
    mac.update(TEXT_ENCODER.encode(normalizeNationalNumber(phone)))
    // Java URLEncoder over base64: only '+', '/' and '=' need escaping.
    return encodeURIComponent(mac.digest('base64'))
}

/**
 * Derive the PBKDF2 key from the package name and `about_logo.png`.
 * Exposed for tooling that extracts the material from an APK.
 */
export function deriveAndroidSecretKey(
    packageName: string,
    aboutLogoPng: Uint8Array
): Uint8Array {
    return new Uint8Array(
        pbkdf2Sync(
            Buffer.concat([Buffer.from(packageName, 'utf8'), Buffer.from(aboutLogoPng)]),
            Buffer.from(ANDROID_SALT),
            ANDROID_PBKDF2_ITERATIONS,
            ANDROID_PBKDF2_KEY_SIZE,
            'sha1'
        )
    )
}

/**
 * Parse the JSON produced by the APK material extractor (base64 fields).
 * Pure — read the file yourself and pass the parsed object.
 */
export function parseAndroidApkMaterial(json: unknown): AndroidApkMaterial {
    if (!json || typeof json !== 'object') {
        throw new Error('android APK material must be a JSON object')
    }
    const record = json as Record<string, unknown>
    const certificates = record.certificates
    if (!Array.isArray(certificates) || certificates.length === 0) {
        throw new Error('android APK material is missing certificates')
    }
    if (typeof record.secretKey !== 'string' || typeof record.classesDexMd5 !== 'string') {
        throw new Error('android APK material is missing secretKey/classesDexMd5')
    }
    return {
        packageName: typeof record.packageName === 'string' ? record.packageName : undefined,
        secretKey: record.secretKey,
        classesDexMd5: record.classesDexMd5,
        certificates: certificates as string[],
        apkVersion: typeof record.apkVersion === 'string' ? record.apkVersion : undefined
    }
}

/**
 * Legacy helper kept for API compatibility. New code should use
 * {@link calculateRegistrationToken}; iOS wants hex, Android wants the
 * URL-encoded base64 returned above.
 */
export function calculateRegistrationTokenBase64(version: string, phone: string): string {
    const national = normalizeNationalNumber(phone)
    const result = md5Bytes(TEXT_ENCODER.encode(IOS_STATIC_TOKEN + md5Hex(version) + national))
    return bytesToBase64(result)
}

function md5Hex(value: string): string {
    return createHash('md5').update(value, 'utf8').digest('hex')
}

function asBytes(value: BytesLike, field: string): Uint8Array {
    if (value instanceof Uint8Array) return value
    if (typeof value !== 'string') {
        throw new Error(`${field} must be Uint8Array or base64 string`)
    }
    return base64ToBytes(value)
}

export { bytesToHex }

/**
 * requestToken() - supports both old and attempted modern variants
 */
export async function requestToken(): Promise<string> {
    return generateRequestToken()
}

export async function requestTokenLegacy(): Promise<string> {
    return generateRequestToken()
}

export async function requestTokenModern(): Promise<string> {
    // Try modern variant format
    return generateRequestToken()
}
