import { x25519 } from '@noble/curves/ed25519.js';
import { gcm } from '@noble/ciphers/aes.js';
import { pbkdf2 } from '@noble/hashes/pbkdf2.js';
import { sha256 } from '@noble/hashes/sha2.js';
import { hkdf } from '@noble/hashes/hkdf.js';
import { bytesToHex, hexToBytes, randomBytes } from '@noble/hashes/utils.js';

export const PRAXIS_PBKDF2_ITERATIONS = 310000;
export const PRAXIS_FILE_MAGIC = 'SFTPRX01';
const CHUNK_SIZE = 1024 * 1024;

function utf8(s: string): Uint8Array {
    return new TextEncoder().encode(s);
}

function b64encode(bytes: Uint8Array): string {
    let binary = '';
    for (let i = 0; i < bytes.length; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return btoa(binary);
}

function b64decode(value: string): Uint8Array {
    const binary = atob(value);
    const out = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
        out[i] = binary.charCodeAt(i);
    }
    return out;
}

function concatBytes(...parts: Uint8Array[]): Uint8Array {
    const total = parts.reduce((n, p) => n + p.length, 0);
    const out = new Uint8Array(total);
    let offset = 0;
    for (const part of parts) {
        out.set(part, offset);
        offset += part.length;
    }
    return out;
}

function zeroize(...arrays: Uint8Array[]): void {
    for (const a of arrays) {
        a.fill(0);
    }
}

export interface DerivedPasswordMaterial {
    loginVerifier: string;
    fileKey: Uint8Array;
    saltB64: string;
}

/** Derive login verifier + file key from password. File key never leaves the browser. */
export async function derivePasswordMaterial(
    password: string,
    saltB64?: string,
    iterations: number = PRAXIS_PBKDF2_ITERATIONS,
): Promise<DerivedPasswordMaterial> {
    const salt = saltB64 ? b64decode(saltB64) : randomBytes(16);
    const master = pbkdf2(sha256, utf8(password), salt, { c: iterations, dkLen: 64 });
    const loginKey = master.slice(0, 32);
    const fileKey = master.slice(32, 64);
    const loginVerifier = bytesToHex(sha256(concatBytes(loginKey, utf8('sft-praxis-login'))));
    zeroize(loginKey, master);
    return {
        loginVerifier,
        fileKey,
        saltB64: b64encode(salt),
    };
}

export function encryptWithKey(key: Uint8Array, plaintext: Uint8Array): string {
    const nonce = randomBytes(12);
    const cipher = gcm(key, nonce);
    const ciphertext = cipher.encrypt(plaintext);
    return b64encode(concatBytes(nonce, ciphertext));
}

export function decryptWithKey(key: Uint8Array, packageB64: string): Uint8Array {
    const packed = b64decode(packageB64);
    const nonce = packed.slice(0, 12);
    const ciphertext = packed.slice(12);
    const cipher = gcm(key, nonce);
    return cipher.decrypt(ciphertext);
}

export interface PraxisKeyBundle {
    praxisKey: Uint8Array;
    publicKeyB64: string;
    halfA: Uint8Array;
    halfB: Uint8Array;
}

export function createPraxisKey(): PraxisKeyBundle {
    const praxisKey = randomBytes(32);
    const halfB = randomBytes(32);
    const halfA = new Uint8Array(32);
    for (let i = 0; i < 32; i++) {
        halfA[i] = praxisKey[i] ^ halfB[i];
    }
    const publicKey = x25519.getPublicKey(praxisKey);
    return {
        praxisKey,
        publicKeyB64: b64encode(publicKey),
        halfA,
        halfB,
    };
}

export function combineHalves(halfA: Uint8Array, halfB: Uint8Array): Uint8Array {
    const praxisKey = new Uint8Array(32);
    for (let i = 0; i < 32; i++) {
        praxisKey[i] = halfA[i] ^ halfB[i];
    }
    return praxisKey;
}

function sealKeyMaterial(sharedSecret: Uint8Array, plaintext: Uint8Array): Uint8Array {
    const aesKey = hkdf(sha256, sharedSecret, undefined, utf8('sft-praxis-seal-v1'), 32);
    const nonce = randomBytes(12);
    const cipher = gcm(aesKey, nonce);
    const ciphertext = cipher.encrypt(plaintext);
    zeroize(aesKey);
    return concatBytes(nonce, ciphertext);
}

function openKeyMaterial(sharedSecret: Uint8Array, packed: Uint8Array): Uint8Array {
    const aesKey = hkdf(sha256, sharedSecret, undefined, utf8('sft-praxis-seal-v1'), 32);
    const nonce = packed.slice(0, 12);
    const ciphertext = packed.slice(12);
    const cipher = gcm(aesKey, nonce);
    const plain = cipher.decrypt(ciphertext);
    zeroize(aesKey);
    return plain;
}

/** Seal 32-byte DEK to praxis X25519 public key. */
export function sealDekToPublicKey(dek: Uint8Array, publicKeyB64: string): string {
    const recipientPub = b64decode(publicKeyB64);
    const ephemeralPriv = randomBytes(32);
    const ephemeralPub = x25519.getPublicKey(ephemeralPriv);
    const shared = x25519.getSharedSecret(ephemeralPriv, recipientPub);
    const sealed = sealKeyMaterial(shared, dek);
    zeroize(ephemeralPriv, shared);
    return b64encode(concatBytes(ephemeralPub, sealed));
}

export function openSealedDek(sealedB64: string, praxisPrivateKey: Uint8Array): Uint8Array {
    const packed = b64decode(sealedB64);
    const ephemeralPub = packed.slice(0, 32);
    const sealed = packed.slice(32);
    const shared = x25519.getSharedSecret(praxisPrivateKey, ephemeralPub);
    const dek = openKeyMaterial(shared, sealed);
    zeroize(shared);
    return dek;
}

/** Seal DEK with a patient code (high-entropy string). */
export function sealDekWithPatientCode(dek: Uint8Array, code: string, saltB64?: string): { sealed: string; salt: string } {
    const salt = saltB64 ? b64decode(saltB64) : randomBytes(16);
    const key = pbkdf2(sha256, utf8(code), salt, { c: PRAXIS_PBKDF2_ITERATIONS, dkLen: 32 });
    const sealedBody = encryptWithKey(key, dek);
    const sealed = b64encode(concatBytes(salt, b64decode(sealedBody)));
    zeroize(key);
    return { sealed, salt: b64encode(salt) };
}

export function openDekWithPatientCode(sealedB64: string, code: string): Uint8Array {
    const packed = b64decode(sealedB64);
    const salt = packed.slice(0, 16);
    const body = b64encode(packed.slice(16));
    const key = pbkdf2(sha256, utf8(code), salt, { c: PRAXIS_PBKDF2_ITERATIONS, dkLen: 32 });
    try {
        return decryptWithKey(key, body);
    } finally {
        zeroize(key);
    }
}

async function encryptFileBytes(plain: Uint8Array, dek: Uint8Array): Promise<Uint8Array> {
    const parts: Uint8Array[] = [utf8(PRAXIS_FILE_MAGIC)];
    let offset = 0;
    while (offset < plain.length) {
        const end = Math.min(offset + CHUNK_SIZE, plain.length);
        const chunk = plain.slice(offset, end);
        const nonce = randomBytes(12);
        const cipher = gcm(dek, nonce);
        const ciphertext = cipher.encrypt(chunk);
        const len = new Uint8Array(4);
        new DataView(len.buffer).setUint32(0, ciphertext.length, false);
        parts.push(len, nonce, ciphertext);
        offset = end;
    }
    return concatBytes(...parts);
}

async function decryptFileBytes(cipherFile: Uint8Array, dek: Uint8Array): Promise<Uint8Array> {
    const magic = new TextDecoder().decode(cipherFile.slice(0, 8));
    if (magic !== PRAXIS_FILE_MAGIC) {
        throw new Error('Invalid praxis ciphertext magic');
    }
    const parts: Uint8Array[] = [];
    let offset = 8;
    while (offset < cipherFile.length) {
        const len = new DataView(cipherFile.buffer, cipherFile.byteOffset + offset, 4).getUint32(0, false);
        offset += 4;
        const nonce = cipherFile.slice(offset, offset + 12);
        offset += 12;
        const ciphertext = cipherFile.slice(offset, offset + len);
        offset += len;
        const cipher = gcm(dek, nonce);
        parts.push(cipher.decrypt(ciphertext));
    }
    return concatBytes(...parts);
}

export async function encryptFileForPraxis(
    file: File | Blob,
    publicKeyB64: string,
    patientCode?: string,
): Promise<{ blob: Blob; sealedDek: string; patientSealedDek: string | null; originalName: string }> {
    const plain = new Uint8Array(await file.arrayBuffer());
    const dek = randomBytes(32);
    try {
        const sealedDek = sealDekToPublicKey(dek, publicKeyB64);
        let patientSealedDek: string | null = null;
        if (patientCode && patientCode.length >= 12) {
            patientSealedDek = sealDekWithPatientCode(dek, patientCode).sealed;
        }
        const cipherBytes = await encryptFileBytes(plain, dek);
        const name = file instanceof File ? file.name : 'file.bin';
        return {
            blob: new Blob([cipherBytes], { type: 'application/octet-stream' }),
            sealedDek,
            patientSealedDek,
            originalName: name,
        };
    } finally {
        zeroize(dek, plain);
    }
}

export async function decryptFileWithDek(cipherBlob: Blob, dek: Uint8Array): Promise<Blob> {
    const cipherBytes = new Uint8Array(await cipherBlob.arrayBuffer());
    const plain = await decryptFileBytes(cipherBytes, dek);
    return new Blob([plain]);
}

export async function decryptPraxisFile(cipherBlob: Blob, sealedDekB64: string, praxisPrivateKey: Uint8Array): Promise<Blob> {
    const dek = openSealedDek(sealedDekB64, praxisPrivateKey);
    try {
        return await decryptFileWithDek(cipherBlob, dek);
    } finally {
        zeroize(dek);
    }
}

export async function wrapHalfBAtKek(
    kekBaseUrl: string,
    publicId: string,
    secret: string,
    halfB: Uint8Array,
    keyVersion: number,
): Promise<string> {
    const response = await fetch(`${kekBaseUrl.replace(/\/$/, '')}/api/keys/wrap`, {
        method: 'POST',
        headers: {
            Authorization: `Bearer ${publicId}:${secret}`,
            'Content-Type': 'application/json',
            Accept: 'application/json',
        },
        body: JSON.stringify({
            dek: b64encode(halfB),
            keyVersion,
        }),
    });
    if (!response.ok) {
        throw new Error(`KEK wrap failed: HTTP ${response.status}`);
    }
    const data = await response.json();
    if (!data.wrappedDek) {
        throw new Error('KEK wrap response missing wrappedDek');
    }
    return data.wrappedDek as string;
}

export async function unwrapHalfBAtKek(
    kekBaseUrl: string,
    publicId: string,
    secret: string,
    wrappedHalfB: string,
    keyVersion: number,
): Promise<Uint8Array> {
    const response = await fetch(`${kekBaseUrl.replace(/\/$/, '')}/api/keys/unwrap`, {
        method: 'POST',
        headers: {
            Authorization: `Bearer ${publicId}:${secret}`,
            'Content-Type': 'application/json',
            Accept: 'application/json',
        },
        body: JSON.stringify({
            wrappedDek: wrappedHalfB,
            keyVersion,
        }),
    });
    if (!response.ok) {
        throw new Error(`KEK unwrap failed: HTTP ${response.status}`);
    }
    const data = await response.json();
    const dekB64 = data.dek as string;
    const halfB = b64decode(dekB64);
    if (halfB.length !== 32) {
        throw new Error('Invalid halfB from KEK');
    }
    return halfB;
}

export { b64encode, b64decode, zeroize, bytesToHex, hexToBytes };
