import fs from 'fs';

const filePath = 'C:/X/workspace/jumpa.id/vc/lib/xcu-quantum-decoder.ts';
let content = fs.readFileSync(filePath, 'utf-8');

// Fix 'any' in detectBestCodec / encoder
content = content.replace(/private trackProcessor: any = null;/g, 'private trackProcessor: unknown = null;');
content = content.replace(/private trackGenerator: any = null;/g, 'private trackGenerator: unknown = null;');
content = content.replace(/output: \(frame: any\) =>/g, 'output: (frame: unknown) =>');
content = content.replace(/error: \(e: any\) =>/g, 'error: (e: unknown) =>');
content = content.replace(/output: async \(chunk: any, meta: any\) =>/g, 'output: async (chunk: { byteLength: number; copyTo: (buf: Uint8Array) => void; type: string; }, meta: unknown) =>');
content = content.replace(/\(window as any\)/g, '(window as unknown as { [key: string]: unknown })');
content = content.replace(/new \(window as unknown as \{ \[key: string\]: unknown \}\)\.EncodedVideoChunk/g, 'new (window as unknown as { EncodedVideoChunk: any }).EncodedVideoChunk');
content = content.replace(/new \(window as unknown as \{ \[key: string\]: unknown \}\)\.MediaStreamTrackProcessor/g, 'new (window as unknown as { MediaStreamTrackProcessor: any }).MediaStreamTrackProcessor');
content = content.replace(/typeof \(window as unknown as \{ \[key: string\]: unknown \}\)\.MediaStreamTrackProcessor/g, 'typeof (window as unknown as { MediaStreamTrackProcessor: unknown }).MediaStreamTrackProcessor');

// Fix SDKs
const wasmSdk1 = 'C:/X/workspace/jumpa.id/vc/public/sdk/xcu/xcom_wasm_sdk.js';
if (fs.existsSync(wasmSdk1)) {
    const wasm = fs.readFileSync(wasmSdk1, 'utf-8');
    if (!wasm.startsWith('/* eslint-disable */')) {
        fs.writeFileSync(wasmSdk1, '/* eslint-disable */\n' + wasm, 'utf-8');
    }
}

const wasmSdk2 = 'C:/X/workspace/jumpa.id/vc/public/sdk/xcu/xcu_wasm_sdk.js';
if (fs.existsSync(wasmSdk2)) {
    const wasm2 = fs.readFileSync(wasmSdk2, 'utf-8');
    if (!wasm2.startsWith('/* eslint-disable */')) {
        fs.writeFileSync(wasmSdk2, '/* eslint-disable */\n' + wasm2, 'utf-8');
    }
}

// Write back
fs.writeFileSync(filePath, content, 'utf-8');
console.log('Fixed typescript errors');
