// Usage: node fetchusr.js <phone>   e.g.  node fetchusr.js 0041787504060

const ADMIN_URL = 'https://ecobeadmin.com/admin/api';
const BOT_TOKEN = '15579990079586356780';
const headers   = { 'Authorization': `Bearer ${BOT_TOKEN}` };

const phone = process.argv[2];
if (!phone) { console.error('Usage: node fetchusr.js <phone>'); process.exit(1); }

async function get(path) {
    const r = await fetch(`${ADMIN_URL}${path}`, { headers });
    if (!r.ok) throw new Error(`${r.status} ${path}`);
    return r.json();
}

const planLabel   = { silver: 'Self-Driven', golden: 'Partnership' };
const statusLabel = { applied: 'Applied', cv_requested: 'CV Requested', under_analysis: 'Under Analysis', rejected: 'Rejected', interview: 'Interview', offer: 'Offer' };

function fmt(iso) { return iso ? new Date(iso).toLocaleDateString('pt-BR') : '—'; }
function hr(char = '─', n = 56) { return char.repeat(n); }

async function main() {
    const slugs = await get('/mentees');

    // Find by phone (normalise to digits only for loose match)
    const digits = s => (s || '').replace(/\D/g, '');
    const target = digits(phone);

    let found = null, cs = null;
    for (const slug of slugs) {
        try {
            const data = await get(`/mentee/${slug}/career-strategy`);
            if (digits(data.phone) === target || digits(data.phoneAlt) === target) {
                found = slug; cs = data; break;
            }
        } catch {}
    }

    if (!found) { console.log(`\nNo client found with phone: ${phone}\n`); return; }

    let jt = null;
    try { jt = await get(`/mentee/${found}/jobtracking`); } catch {}

    // ── Header ──────────────────────────────────────────────────────
    console.log(`\n${hr('═')}`);
    console.log(`  ${cs.leadName}`);
    console.log(hr('═'));

    // ── Profile ──────────────────────────────────────────────────────
    console.log('\n  PROFILE');
    console.log(hr());
    const fields = [
        ['Email',       cs.email],
        ['Email alt',   cs.emailAlt],
        ['Phone',       cs.phone],
        ['Phone alt',   cs.phoneAlt],
        ['Location',    cs.location],
        ['Nationality', cs.nationality],
        ['Languages',   Array.isArray(cs.languages) ? cs.languages.join(', ') : cs.languages],
        ['LinkedIn',    cs.linkedin],
        ['Plan',        planLabel[cs.plan] || cs.plan],
        ['Phase',       cs.phase],
        ['Entry date',  fmt(cs.entryDate || cs.createdAt)],
    ];
    for (const [label, val] of fields) {
        if (val) console.log(`  ${label.padEnd(14)} ${val}`);
    }

    // ── Career Strategy ───────────────────────────────────────────────
    console.log('\n  CAREER STRATEGY');
    console.log(hr());
    const strat = [
        ['Target roles',    (cs.primaryRoles || []).slice(0, 3).join(', ')],
        ['Target sectors',  Array.isArray(cs.targetSectors) ? cs.targetSectors.slice(0, 3).join(', ') : Object.values(cs.targetSectors || {}).flat().slice(0, 3).join(', ')],
        ['Target cities',   (cs.priorityCities || []).slice(0, 3).join(', ')],
        ['Seniority',       cs.seniority],
        ['Salary target',   cs.salaryTarget],
        ['Open to remote',  cs.openToRemote],
        ['Open to relocate',cs.openToRelocate],
        ['Work permits',    Array.isArray(cs.workPermits) ? cs.workPermits.join(', ') : cs.workPermits],
        ['Positioning',     cs.targetPositioning],
    ];
    for (const [label, val] of strat) {
        if (val) console.log(`  ${label.padEnd(18)} ${val}`);
    }
    if (cs.shortDescription) console.log(`\n  "${cs.shortDescription}"`);

    // ── Jobs ──────────────────────────────────────────────────────────
    const jobs = (jt && jt.jobs) || [];
    console.log(`\n  JOBS  (${jobs.length} total)`);
    console.log(hr());

    if (!jobs.length) {
        console.log('  No jobs tracked yet.');
    } else {
        jobs.forEach((j, i) => {
            const status = statusLabel[j.status] || j.status || '—';
            console.log(`\n  ${i + 1}. [${status}]  ${j.title}`);
            console.log(`     Company   ${j.company}`);
            console.log(`     Location  ${j.location || '—'}`);
            console.log(`     Found     ${fmt(j.foundAt)}    Source: ${j.source || '—'}`);
            if (j.status === 'applied' && j.appliedAt) console.log(`     Applied   ${fmt(j.appliedAt)}`);
            if (j.aiReason)  console.log(`     AI note   ${j.aiReason}`);
            if (j.notes)     console.log(`     Notes     ${j.notes}`);
            if (j.url)       console.log(`     URL       ${j.url}`);
        });
    }

    console.log(`\n${hr('═')}\n`);
}

main().catch(console.error);
