import puppeteer from '/home/moonui/public_html/presentation/albassit/node_modules/puppeteer-core/lib/esm/puppeteer/puppeteer-core.js';
import { mkdirSync } from 'fs';

const appUrl = 'https://moonui.elbaset.com/app';
const out = '/home/moonui/public_html/presentation/screens';
mkdirSync(out, { recursive: true });

const browser = await puppeteer.launch({
    headless: 'new',
    args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
    executablePath: '/root/.cache/puppeteer/chrome/linux-146.0.7680.153/chrome-linux64/chrome'
});

const page = await browser.newPage();
await page.setViewport({ width: 1366, height: 800 });

// Login
console.log('Logging in...');
await page.goto(`${appUrl}/auth/login`, { waitUntil: 'networkidle2', timeout: 30000 });
await new Promise(r => setTimeout(r, 3000));
await page.type('input[type="email"], input[formcontrolname="email"]', 'hazem@gt4it.com');
await page.type('input[type="password"], input[formcontrolname="password"]', '123456789');
await page.click('button[type="submit"]');
await new Promise(r => setTimeout(r, 6000));

async function shot(name, path) {
    try {
        await page.goto(`${appUrl}${path}`, { waitUntil: 'networkidle0', timeout: 25000 });
        await new Promise(r => setTimeout(r, 5000));
        await page.screenshot({ path: `${out}/${name}.png`, fullPage: false });
        const url = page.url();
        console.log(`✓ ${name} → ${url.split('/app')[1] || '/'}`);
    } catch(e) {
        try {
            await page.goto(`${appUrl}${path}`, { waitUntil: 'networkidle2', timeout: 20000 });
            await new Promise(r => setTimeout(r, 5000));
            await page.screenshot({ path: `${out}/${name}.png`, fullPage: false });
            console.log(`✓ ${name} (retry)`);
        } catch(e2) {
            console.log(`✗ ${name}: ${e2.message.substring(0, 60)}`);
        }
    }
}

// CRM
await shot('crm-tickets', '/crm/tickets');
await shot('crm-customers', '/crm/customers');

// Production
await shot('production-orders', '/production/orders');
await shot('production-boms', '/production/boms');
await shot('production-centers', '/production/centers');

// QMS
await shot('qms-inspections', '/qms/inspections');
await shot('qms-ncr', '/qms/non-conformances');

// CMMS
await shot('cmms-assets', '/cmms/assets');
await shot('cmms-work-orders', '/cmms/work-orders');

await browser.close();
console.log('Done!');
