'use strict';

const apify = require('./apify');
const claude = require('./claude');
const { runConcentricSearch } = require('./concentric');
const db = require('./db');

let _dbReady = false;
async function ensureDb() {
    if (_dbReady) return;
    await db.initDb();
    _dbReady = true;
}

async function runOutreachDiscovery({ target_company, target_role, linkedin_url, target_company_linkedin }) {
    await ensureDb();

    let applicantAttrs = { schools: [], locations: [], companies: [], industries: [], languages: [], skills: [] };
    if (linkedin_url) {
        try {
            const profile = await apify.scrapeProfile(linkedin_url);
            applicantAttrs = await claude.extractProfileAttributes(profile);
        } catch (e) {
            console.error('[outreach] extractProfileAttributes failed:', e.message);
        }
    }

    let candidates = [];
    try {
        ({ candidates } = await runConcentricSearch({
            applicantAttrs,
            targetCompany: target_company,
            targetCompanyLinkedin: target_company_linkedin || null,
            csvConnections: [],
        }));
    } catch (e) {
        console.error('[outreach] runConcentricSearch failed:', e.message);
    }

    if (!candidates || !candidates.length) return [];

    // Strip raw Apify fields — only send what Claude needs for scoring
    const clean = candidates.map(c => ({
        name:                 c.name || '',
        title:                c.title || '',
        linkedin_url:         c.linkedin_url || '',
        location:             c.location || '',
        schools:              (c.schools || []).slice(0, 5),
        companies:            (c.companies || []).slice(0, 5),
        industries:           (c.industries || []).slice(0, 3),
        languages:            (c.languages || []).slice(0, 5),
        is_direct_connection: c.is_direct_connection || false,
    }));

    try {
        const matches = await claude.scoreAndRank(applicantAttrs, clean, target_company);
        return matches.slice(0, 3);
    } catch (e) {
        console.error('[outreach] scoreAndRank failed:', e.message);
        return [];
    }
}

module.exports = { runOutreachDiscovery };
