File size: 12,098 Bytes
bd28470
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/**
 * Contact Enricher v2 β€” Full Pipeline
 * 
 * Step 1: Find emails (Hunter.io + Pattern Generator + SMTP verify)
 *         Snov.io REMOVED β€” replaced by FREE email pattern generation
 * Step 2: Classify emails (Tier 1/2/3)
 * Step 3: Verify emails (7-layer deep)
 * Step 4: Find personal LinkedIn
 * Step 5: Find social profiles
 * Step 6: Filter for decision-makers only
 * 
 * Output: Verified, classified contacts ready for Phase 2
 */

import { searchHunterContacts, type HunterContact } from "../providers/hunter";
import { generateAndVerifyEmails, findEmailForPerson } from "./email-pattern-generator";
import { classifyEmail, type ClassificationResult } from "./email-classifier";
import { verifyEmailDeep, type VerificationResult } from "./email-verifier";
import { findPersonalLinkedIn, type PersonalLinkedIn } from "./linkedin-person-finder";
import { findSocialProfiles, type SocialProfiles } from "./social-finder";
import { getSupabaseClient } from "../../shared/supabase/client";
import { logger } from "../../shared/utils/logger";
import { randomUUID } from "crypto";

export interface EnrichedContact {
  id: string;
  companyId: string;
  fullName: string;
  title: string | null;
  seniority: string | null;

  // Email intelligence
  email: string | null;
  emailTier: string;                       // 'personal' | 'authority' | 'context_verified' | 'rejected'
  emailVerification: VerificationResult | null;
  emailClassification: ClassificationResult | null;

  // LinkedIn (both company and personal)
  linkedinPersonalUrl: string | null;
  linkedinPersonalConfidence: number;

  // Social
  socialProfiles: SocialProfiles | null;

  // Authority
  authorityConfirmed: boolean;
  authorityReason: string;

  // Source tracking
  source: "hunter" | "pattern" | "combined";
  providerConfidence: number;
}

/**
 * Full contact enrichment pipeline for a company.
 */
export async function enrichContacts(
  companyId: string,
  domain: string,
  companyName: string,
  employeeCount: number | null,
  industry: string,
  websiteSnippet: string,
  websiteHtml: string,
  companyLinkedInUrl: string | null,
  traceId: string
): Promise<EnrichedContact[]> {
  logger.info({ domain, companyName }, "Starting contact enrichment pipeline");

  // ── Step 1: Find emails from all providers ─────────────────
  const rawContacts = await findAllContacts(domain);
  
  if (rawContacts.length === 0) {
    logger.info({ domain }, "No contacts found from any provider");
    return [];
  }

  logger.info({ domain, found: rawContacts.length }, "Raw contacts from providers");

  // ── Step 2-6: Process each contact ─────────────────────────
  const enriched: EnrichedContact[] = [];

  for (const raw of rawContacts) {
    if (!raw.email) continue;

    // Step 2: Classify email (Tier 1/2/3)
    const classification = await classifyEmail(
      raw.email,
      { name: companyName, employeeCount, industry, websiteSnippet },
      traceId
    );

    // Rejected by classifier β†’ skip entirely
    if (classification.verdict === "rejected") {
      logger.debug({ email: raw.email, reason: classification.reason }, "Email rejected by classifier");
      continue;
    }

    // Step 3: Deep verification (7 layers)
    const verification = await verifyEmailDeep(
      raw.email,
      domain,
      raw.confidence
    );

    // Hard invalid β†’ skip
    if (verification.status === "rejected_invalid") {
      logger.debug({ email: raw.email }, "Email rejected by 7-layer verifier");
      continue;
    }

    // Step 4: Find personal LinkedIn
    let linkedin: PersonalLinkedIn | null = null;
    if (raw.fullName && raw.fullName.length > 3) {
      linkedin = await findPersonalLinkedIn(
        raw.fullName,
        companyName,
        domain,
        companyLinkedInUrl
      );
    }

    // Step 5: Social profiles (once per company, not per contact)
    // Social will be fetched separately at company level

    // Step 6: Authority check
    const { confirmed, reason } = checkAuthority(raw, classification);

    const contact: EnrichedContact = {
      id: randomUUID(),
      companyId,
      fullName: raw.fullName,
      title: raw.title,
      seniority: raw.seniority,
      email: raw.email,
      emailTier: classification.verdict,
      emailVerification: verification,
      emailClassification: classification,
      linkedinPersonalUrl: linkedin?.url ?? null,
      linkedinPersonalConfidence: linkedin?.confidence ?? 0,
      socialProfiles: null,  // set at company level
      authorityConfirmed: confirmed,
      authorityReason: reason,
      source: raw.source,
      providerConfidence: raw.confidence,
    };

    enriched.push(contact);
  }

  // Sort: authority-confirmed first, then by verification confidence
  enriched.sort((a, b) => {
    if (a.authorityConfirmed !== b.authorityConfirmed) return a.authorityConfirmed ? -1 : 1;
    return (b.emailVerification?.overallConfidence ?? 0) - (a.emailVerification?.overallConfidence ?? 0);
  });

  // Step 5: Social profiles for company (once)
  if (enriched.length > 0) {
    const social = await findSocialProfiles(domain, companyName, websiteHtml);
    for (const c of enriched) {
      c.socialProfiles = social;
    }
  }

  logger.info({
    domain,
    rawFound: rawContacts.length,
    afterClassification: enriched.length,
    authorityConfirmed: enriched.filter(c => c.authorityConfirmed).length,
    withLinkedIn: enriched.filter(c => c.linkedinPersonalUrl).length,
  }, "Contact enrichment pipeline complete");

  // Save to database
  await saveContacts(enriched);

  return enriched;
}

// ─── Find contacts from all providers ─────────────────────────
// Strategy: Hunter.io (free 25/mo) for names+titles+emails
//           Pattern Generator (FREE, unlimited) to find more emails
//           Snov.io REMOVED β€” replaced by pattern generation

interface RawContact {
  fullName: string;
  email: string;
  title: string | null;
  seniority: string | null;
  confidence: number;
  source: "hunter" | "pattern";
}

async function findAllContacts(domain: string): Promise<RawContact[]> {
  const contacts: RawContact[] = [];
  const seenEmails = new Set<string>();
  const namesFromHunter: { firstName: string; lastName: string; title: string | null; seniority: string | null }[] = [];

  // ── Source 1: Hunter.io (25 free/month) ─────────────────────
  // Hunter gives us NAMES + TITLES + EMAILS
  try {
    const hunterResults = await searchHunterContacts(domain);
    for (const h of hunterResults) {
      const email = h.value?.toLowerCase();
      const firstName = h.first_name ?? "";
      const lastName = h.last_name ?? "";
      const fullName = `${firstName} ${lastName}`.trim();

      // Save name for pattern generation later
      if (firstName && lastName) {
        namesFromHunter.push({
          firstName,
          lastName,
          title: h.position ?? null,
          seniority: h.seniority ?? null,
        });
      }

      if (email && !seenEmails.has(email)) {
        seenEmails.add(email);
        contacts.push({
          fullName,
          email,
          title: h.position ?? null,
          seniority: h.seniority ?? null,
          confidence: h.confidence ?? 0,
          source: "hunter",
        });
      }
    }
  } catch (err) {
    logger.warn({ domain, err }, "Hunter search failed β€” falling back to pattern generation");
  }

  // ── Source 2: Pattern Generator (FREE, UNLIMITED) ──────────
  // For names we got from Hunter that DON'T have emails,
  // OR if Hunter returned no results at all
  for (const person of namesFromHunter) {
    // Check if we already have an email for this person
    const hasEmail = contacts.some(c =>
      c.fullName.toLowerCase().includes(person.firstName.toLowerCase()) &&
      c.fullName.toLowerCase().includes(person.lastName.toLowerCase())
    );

    if (!hasEmail) {
      // Generate email patterns and SMTP verify (FREE)
      const generated = await findEmailForPerson(
        `${person.firstName} ${person.lastName}`,
        domain
      );

      if (generated && generated.smtpStatus === "deliverable" && !seenEmails.has(generated.email)) {
        seenEmails.add(generated.email);
        contacts.push({
          fullName: `${person.firstName} ${person.lastName}`,
          email: generated.email,
          title: person.title,
          seniority: person.seniority,
          confidence: generated.confidence * 100,
          source: "pattern",
        });
      }
    }
  }

  // ── Source 3: If still no contacts, try common owner patterns ─
  if (contacts.length === 0) {
    // Try generic owner/manager patterns
    const ownerPatterns = ["info", "contact", "hello", "admin"];
    for (const prefix of ownerPatterns) {
      const email = `${prefix}@${domain}`;
      if (!seenEmails.has(email)) {
        seenEmails.add(email);
        contacts.push({
          fullName: "Unknown",
          email,
          title: null,
          seniority: null,
          confidence: 20,
          source: "pattern",
        });
      }
    }
  }

  logger.info({
    domain,
    hunterContacts: contacts.filter(c => c.source === "hunter").length,
    patternContacts: contacts.filter(c => c.source === "pattern").length,
    total: contacts.length,
  }, "Contact finding complete (Hunter + Pattern Generator)");

  return contacts;
}

// ─── Authority check ─────────────────────────────────────────

function checkAuthority(
  contact: RawContact,
  classification: ClassificationResult
): { confirmed: boolean; reason: string } {
  // Personal email with senior title β†’ confirmed
  const seniorTitles = /\b(ceo|cto|coo|cfo|cmo|founder|co-founder|owner|partner|director|vp|vice\s*president|president|head|principal|managing|general\s*manager)\b/i;

  if (classification.verdict === "personal" && contact.title && seniorTitles.test(contact.title)) {
    return { confirmed: true, reason: `Personal email + senior title: ${contact.title}` };
  }

  if (classification.verdict === "authority") {
    return { confirmed: true, reason: `Authority email prefix: ${contact.email.split("@")[0]}` };
  }

  if (classification.verdict === "personal") {
    return { confirmed: true, reason: "Personal email format β€” likely individual decision maker" };
  }

  if (classification.verdict === "context_verified" && classification.confidence >= 0.7) {
    return { confirmed: true, reason: classification.reason };
  }

  if (classification.verdict === "outsourcing") {
    return { confirmed: false, reason: "Outsourcing/vendor email β€” may reach procurement, not decision maker" };
  }

  return { confirmed: false, reason: "Authority not confirmed" };
}

// ─── Save to database ────────────────────────────────────────

async function saveContacts(contacts: EnrichedContact[]): Promise<void> {
  const db = getSupabaseClient();

  for (const c of contacts) {
    try {
      await db.from("contacts").upsert({
        id: c.id,
        company_id: c.companyId,
        full_name: c.fullName,
        title: c.title,
        seniority: c.seniority,
        email: c.email,
        email_verified: c.emailVerification?.status === "verified_deliverable",
        email_tier: c.emailTier,
        email_verification_layers: c.emailVerification?.layers ?? {},
        linkedin_personal_url: c.linkedinPersonalUrl,
        social_profiles: c.socialProfiles ?? {},
        authority_confirmed: c.authorityConfirmed,
        confidence: c.emailVerification?.overallConfidence ?? c.providerConfidence,
        source: c.source,
      }, { onConflict: "company_id,email" });
    } catch (err) {
      logger.warn({ email: c.email, err }, "Contact save failed β€” continuing");
    }
  }
}