/**
 * XCU CHAOS MONKEY (NETWORK DEGRADATION KINETIC UDP)
 * 
 * Modul ini melakukan Monkey-Patching pada antarmuka WebTransport bawaan browser.
 * Berfungsi untuk secara artifisial mencekik aliran QUIC, menyuntikkan packet loss,
 * dan menambahkan latensi untuk menguji batas absolut dari XCUQuantumMatrix (Anti-Lag).
 */

export class XCUChaosMonkey {
    private static originalWebTransport: (new (url: string, options?: unknown) => WebTransport) | null = null;
    public static packetLossRatio: number = 0; // 0.0 to 1.0
    public static artificialLatencyMs: number = 0; // in milliseconds
    public static isActive: boolean = false;

    public static unleash(packetLoss: number = 0.2, latency: number = 100) {
        if (typeof window === 'undefined') return;
        if (!('WebTransport' in window)) return;

        if (!this.originalWebTransport) {
            this.originalWebTransport = (window as unknown as { WebTransport: new (url: string, options?: unknown) => WebTransport }).WebTransport;
        }

        this.packetLossRatio = packetLoss;
        this.artificialLatencyMs = latency;
        this.isActive = true;

        console.warn(`[CHAOS MONKEY] TERLEPAS! Packet Loss: ${packetLoss * 100}%, Latency: ${latency}ms`);

        // Monkey-Patch WebTransport
        (window as unknown as { WebTransport: unknown }).WebTransport = class MockWebTransport {
            private _realTransport: WebTransport;
            public ready: Promise<void>;
            public closed: Promise<WebTransportCloseInfo>;
            public datagrams: { readable: ReadableStream, writable: WritableStream } | undefined;

            constructor(url: string, options?: unknown) {
                if (!XCUChaosMonkey.originalWebTransport) throw new Error("WebTransport not found");
                this._realTransport = new XCUChaosMonkey.originalWebTransport(url, options);
                this.ready = this._realTransport.ready;
                this.closed = this._realTransport.closed;
                
                this.datagrams = this._realTransport.datagrams ? {
                    readable: this._realTransport.datagrams.readable,
                    writable: this._realTransport.datagrams.writable
                } : undefined;
            }

            public async createBidirectionalStream() {
                const realStream = await this._realTransport.createBidirectionalStream();
                
                return {
                    readable: realStream.readable, // Biarkan Downlink murni
                    writable: new WritableStream({
                        write: async (chunk) => {
                            if (XCUChaosMonkey.isActive) {
                                // 1. Simulate Packet Loss
                                if (Math.random() < XCUChaosMonkey.packetLossRatio) {
                                    // Paket dijatuhkan ke dalam Blackhole Kuantum
                                    // console.log("[CHAOS MONKEY] Packet Dropped!");
                                    return; 
                                }

                                // 2. Simulate Latency
                                if (XCUChaosMonkey.artificialLatencyMs > 0) {
                                    await new Promise(r => setTimeout(r, XCUChaosMonkey.artificialLatencyMs));
                                }
                            }

                            // Teruskan ke Stream Asli
                            const writer = realStream.writable.getWriter();
                            try {
                                await writer.write(chunk);
                            } finally {
                                writer.releaseLock();
                            }
                        },
                        close() {
                            return realStream.writable.close();
                        },
                        abort(reason) {
                            return realStream.writable.abort(reason);
                        }
                    })
                };
            }

            public close() {
                this._realTransport.close();
            }
        };
    }

    public static contain() {
        if (!this.isActive || typeof window === 'undefined' || !this.originalWebTransport) return;
        
        (window as unknown as { WebTransport: unknown }).WebTransport = this.originalWebTransport;
        this.isActive = false;
        console.log("[CHAOS MONKEY] DIKANDANGKAN. WebTransport kembali murni.");
    }
}
