const path = require('path')
const fs = require('fs')
const Pptr = require('./puppeteer')

module.exports = class AI {
    static async pdfToHtml(pdfFilePath) {
        const browser = await Pptr.init()
        const page = await Pptr.newPage()

        const downloadPath = path.resolve(__dirname, '../uploads/html')
        fs.mkdirSync(downloadPath, { recursive: true })

        const client = await page.target().createCDPSession()
        await client.send('Page.setDownloadBehavior', {
            behavior: 'allow',
            downloadPath: downloadPath,
        })

        await page.goto('https://www.maxai.co/pdf-tools/pdf-to-html/', {
            waitUntil: 'networkidle2',
        })

        const inputSelector = 'input[type=file].css-1gcv6dl'
        const inputUpload = await page.$(inputSelector)
        await inputUpload.uploadFile(pdfFilePath)

        console.log('[MAXAI] PDF diupload:', pdfFilePath)

        await this.clickButtonByText(page, "Finish", { timeout: 60000 })
        console.log("[MAXAI] Klik tombol Finish")

        console.log("[MAXAI] Menunggu tombol Download muncul...")
        await page.waitForFunction(
            () => {
                const buttons = [...document.querySelectorAll("button")]
                return buttons.some(b => b.innerText.includes("Download"))
            },
            { timeout: 120000 }
        )

        await this.clickButtonByText(page, "Download", { timeout: 60000 })
        console.log("[MAXAI] Klik tombol Download")

        const waitForFile = async () => {
            return new Promise((resolve, reject) => {
                const timeout = setTimeout(() => reject('Timeout menunggu file download'), 60000)

                fs.watch(downloadPath, (event, filename) => {
                    if (filename && filename.endsWith('.html')) {
                        clearTimeout(timeout)
                        resolve(path.join(downloadPath, filename))
                    }
                })
            })
        }

        const downloadedFile = await waitForFile()
        console.log('[MAXAI] File HTML tersimpan:', downloadedFile)

        await page.close()
        await browser.close()

        return downloadedFile
    }

    static async clickButtonByText(page, text, options = { timeout: 60000 }) {
        try {
            await page.waitForFunction(
                (t) => {
                    const buttons = [...document.querySelectorAll("button")];
                    return buttons.find(b => b.innerText.includes(t));
                },
                options,
                text
            )

            const handle = await page.evaluateHandle((t) => {
                const buttons = [...document.querySelectorAll("button")];
                return buttons.find(b => b.innerText.includes(t));
            }, text)

            if (!handle) throw new Error(`Button with text "${text}" not found`)

            const element = handle.asElement()
            if (!element) throw new Error(`Button "${text}" is not a valid element`)

            await element.evaluate(el => el.scrollIntoView({ behavior: 'smooth', block: 'center' }))

            await page.waitForFunction(
                (t) => {
                    const btn = [...document.querySelectorAll("button")].find(b => b.innerText.includes(t))
                    return btn && !btn.disabled
                },
                { timeout: 10000 },
                text
            )

            try {
                await element.click({ delay: 50 })
            } catch (err) {
                console.warn(`[AI] .click() gagal, fallback ke DOM click() untuk tombol: ${text}`)
                await page.evaluate(el => el.click(), element)
            }

            console.log(`[AI] Clicked button with text: ${text}`)
        } catch (err) {
            const allButtons = await page.evaluate(() => {
                return [...document.querySelectorAll("button")].map(b => b.innerText.trim())
            })
            console.error(`[AI] clickButtonByText failed: ${err.message}`)
            console.error(`[AI] Semua tombol di halaman: ${JSON.stringify(allButtons)}`)
            throw err
        }
    }
}
