const puppeteer = require('puppeteer');

async function loginToMAM(username, password) {
    try {
        const browser = await puppeteer.launch({
            executablePath: '/usr/bin/chromium-browser',
            headless: true,
            args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu', 'diable-dev-shm-usage']
        });
        const page = await browser.newPage();

        console.log("Navigating to MAM login...");
        await page.goto('https://www.myanonamouse.net/login.php', {
            waitUntil: 'networkidle2',
            timeout: 10000
        });

        const pageTitle = await page.title();

        console.log("Filling in login form...");
        await page.type('input[name="email"]', username);
        await page.type('input[name="password"]', password);

        console.log("Submitting login form...");
        await page.click('input[type="submit"]');
        await page.waitForNavigation({
            waitUntil: 'domcontentloaded',
            timeout: 10000
        });

        console.log("Login attempt completed.");
        const cookies = await page.cookies();
        await browser.close();

        console.log(JSON.stringify(cookies));
    } catch (err) {
        console.error("Login failed: ", err);
        process.exit(1);
    }
}

const username = process.env.MAM_USERNAME;
const password = process.env.MAM_PASSWORD;

loginToMAM(username, password)
    .then(cookies => ({ result: 'Success', cookies }))
    .catch(err => ({ result: 'Error', error: err.message }));
