#!/bin/bash
# Quick fix script for server deployment

echo "=== Quick Server Fix ==="

# 1. Fix Node.js module resolution
cd /var/www/apper/admin.apper

echo "Reinstalling puppeteer-core..."
npm uninstall puppeteer-core
npm install puppeteer-core --save

# 2. Create a simple server-compatible test script
cat > server_scraper.mjs << 'EOF'
import puppeteer from 'puppeteer-core';
import { execFileSync } from 'child_process';

// Auto-detect browser
function detectBrowser() {
    const paths = [
        '/usr/bin/chromium-browser',
        '/usr/bin/google-chrome',
        '/usr/bin/google-chrome-stable'
    ];

    for (const path of paths) {
        try {
            execFileSync('test', ['-x', path]);
            console.log(`Found browser: ${path}`);
            return path;
        } catch {
            continue;
        }
    }
    return null;
}

async function scrapeMarketPrice(ean) {
    console.log(`\n=== Searching for EAN: ${ean} ===`);

    const browserPath = detectBrowser();
    if (!browserPath) {
        throw new Error('No suitable browser found');
    }

    const browser = await puppeteer.launch({
        executablePath: browserPath,
        headless: true,
        args: [
            '--no-sandbox',
            '--disable-setuid-sandbox',
            '--disable-dev-shm-usage',
            '--disable-gpu'
        ]
    });

    try {
        const page = await browser.newPage();
        await page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');

        // Search
        const searchUrl = `https://marketkarsilastir.com/ara?q=${encodeURIComponent(ean)}`;
        console.log(`Search URL: ${searchUrl}`);
        await page.goto(searchUrl, { waitUntil: 'networkidle2', timeout: 30000 });

        // Extract product URL
        const productUrl = await page.evaluate(() => {
            // Try onclick method
            const onClickEl = document.querySelector('[onclick*="window.location.href"]');
            if (onClickEl) {
                const match = onClickEl.getAttribute('onclick').match(/window\.location\.href='([^']+)'/);
                if (match) return match[1];
            }

            // Try direct links
            const links = document.querySelectorAll('a[href*="/fiyat/"]');
            return links.length > 0 ? links[0].href : null;
        });

        if (!productUrl) {
            console.log('✗ No product found');
            return null;
        }

        console.log(`✓ Product URL: ${productUrl}`);

        // Go to product page
        await page.goto(productUrl, { waitUntil: 'networkidle2', timeout: 30000 });

        // Extract prices with validation
        const priceData = await page.evaluate(() => {
            const prices = {};

            // Look for price list structure
            const priceList = document.querySelector('.price-list');
            if (priceList) {
                const elements = priceList.querySelectorAll('*');
                elements.forEach(el => {
                    const text = el.textContent.trim();

                    // Match market and price in same element or nearby
                    const marketMatch = text.match(/(Carrefour|Migros|Şok|A101|File|Mopaş|Bim|Tarım Kredi)/i);
                    const priceMatch = text.match(/(\d+[,.]\d+)\s*[₺TL]/);

                    if (marketMatch && priceMatch) {
                        const price = parseFloat(priceMatch[1].replace(',', '.'));
                        if (price > 0) { // Filter invalid prices
                            prices[marketMatch[1]] = price;
                        }
                    }
                });
            }

            return Object.keys(prices).length > 0 ? prices : null;
        });

        if (priceData) {
            console.log(`✓ Found ${Object.keys(priceData).length} prices:`);
            Object.entries(priceData).forEach(([market, price]) => {
                console.log(`  ${market}: ${price} TRY`);
            });

            // Find best price
            const entries = Object.entries(priceData);
            const best = entries.reduce((min, entry) => entry[1] < min[1] ? entry : min);
            console.log(`\n★ Best price: ${best[1]} TRY at ${best[0]}`);

            return {
                ean: ean,
                url: productUrl,
                prices: priceData,
                best_price: best[1],
                best_market: best[0]
            };
        } else {
            console.log('✗ No valid prices found');
            return null;
        }

    } finally {
        await browser.close();
    }
}

// Test with known working EAN
const testEan = '8690526076379';
scrapeMarketPrice(testEan)
    .then(result => {
        if (result) {
            console.log('\n🎉 SUCCESS: Price scraping working on server!');
        } else {
            console.log('\n❌ FAILED: Could not extract prices');
        }
    })
    .catch(error => {
        console.error('\n💥 ERROR:', error.message);
        process.exit(1);
    });
EOF

echo "Testing server scraper..."
node server_scraper.mjs
