
const Database = require('better-sqlite3');
const path = require('path');

const dbPath = path.resolve(__dirname, '../dev.db');
const db = new Database(dbPath);

const userAgent = 'LeadForge-App/1.0 (https://github.com/leadforge; support@leadforge.example.com)';

async function fetchLeads(keyword, location) {
    console.log(`[Script] Geocoding location: ${location}`);
    const nomRes = await fetch(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(location)}&format=json&limit=1`, {
        headers: { 'User-Agent': userAgent }
    });
    
    if (!nomRes.ok) {
        throw new Error(`Geocoding failed: ${nomRes.status}`);
    }
    
    const nomData = await nomRes.json();
    if (!nomData || !nomData.length) {
        throw new Error('Location not found');
    }
    
    const bboxArr = nomData[0].boundingbox;
    let south = parseFloat(bboxArr[0]);
    let north = parseFloat(bboxArr[1]);
    let west = parseFloat(bboxArr[2]);
    let east = parseFloat(bboxArr[3]);
    
    // Expand if too tight
    if (Math.abs(north - south) < 0.01 || Math.abs(east - west) < 0.01) {
         south -= 0.05; north += 0.05; west -= 0.05; east += 0.05;
    }

    const overpassQuery = `
      [out:json][timeout:25];
      (
        nwr[amenity="${keyword}"](${south},${west},${north},${east});
        nwr[shop="${keyword}"](${south},${west},${north},${east});
        nwr[amenity~"${keyword}",i](${south},${west},${north},${east});
        nwr[shop~"${keyword}",i](${south},${west},${north},${east});
        nwr[name~"${keyword}",i](${south},${west},${north},${east});
      );
      out center 150;
    `;
    
    console.log(`[Script] Querying Overpass API...`);
    const osmRes = await fetch('https://overpass-api.de/api/interpreter', {
        method: 'POST',
        body: 'data=' + encodeURIComponent(overpassQuery),
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': userAgent
        }
    });

    if (!osmRes.ok) {
        throw new Error(`Overpass API failed: ${osmRes.status}`);
    }

    const osmData = await osmRes.json();
    return osmData.elements || [];
}

function calculateScore(tags) {
    let score = 30;
    if (tags.phone || tags['contact:phone']) score += 20;
    if (tags.email || tags['contact:email']) score += 30;
    if (tags.website || tags['contact:website']) score += 20;
    if (tags.opening_hours) score += 10;
    return Math.min(score, 100) / 100;
}

async function main() {
    const keyword = 'restaurant';
    const location = 'Colombo, Sri Lanka';
    
    try {
        const elements = await fetchLeads(keyword, location);
        console.log(`[Script] Found ${elements.length} elements.`);
        
        const insert = db.prepare(`
            INSERT INTO Lead (id, businessName, website, email, phone, address, city, category, source, confidenceScore, rawData, status, createdAt, updatedAt)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `);

        let savedCount = 0;
        const resultsToShow = [];

        for (const e of elements) {
            const tags = e.tags || {};
            const businessName = tags.name || 'Unnamed Business';
            
            // Skip unnamed or generic ones for better "real world" feel if possible
            if (businessName === 'Unnamed Business' && savedCount > 50) continue;

            const id = `cuid_${Math.random().toString(36).substr(2, 9)}`;
            const website = tags.website || tags['contact:website'] || tags.url || null;
            const email = tags.email || tags['contact:email'] || null;
            const phone = tags.phone || tags['contact:phone'] || null;
            const address = tags['addr:street'] ? `${tags['addr:housenumber'] || ''} ${tags['addr:street']}`.trim() : location;
            const city = tags['addr:city'] || 'Colombo';
            const category = tags.amenity || tags.shop || keyword;
            const score = calculateScore(tags);
            const now = new Date().toISOString();

            try {
                insert.run(
                    id, businessName, website, email, phone, address, city, category, 'Overpass', score, JSON.stringify(e), 'new', now, now
                );
                savedCount++;
                if (resultsToShow.length < 60) {
                    resultsToShow.push({ businessName, website, phone, address, score: (score * 100).toFixed(0) + '%' });
                }
            } catch (err) {
                // Ignore duplicates or other DB errors
            }
        }

        console.log(`[Script] Saved ${savedCount} leads to DB.`);
        console.log('RESULTS_START');
        console.log(JSON.stringify(resultsToShow, null, 2));
        console.log('RESULTS_END');

    } catch (err) {
        console.error('Error:', err.message);
    } finally {
        db.close();
    }
}

main();
