@xuda.io/ai_module 1.1.4766 → 1.1.4768

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.mjs +2544 -3082
  2. package/old.mjs +2688 -0
  3. package/package.json +1 -1
package/old.mjs CHANGED
@@ -2086,3 +2086,2691 @@ for await (let account_profile of profile_requests_from_res.docs) {
2086
2086
  // return 'unknown';
2087
2087
  // }
2088
2088
  // };
2089
+
2090
+
2091
+
2092
+ // export const get_business_info = async function (uid, name, email, account_profile_info) {
2093
+ // // ========== HELPER FUNCTIONS ==========
2094
+
2095
+ // function validatePhoneNumber(phone) {
2096
+ // if (!phone || phone.toLowerCase() === 'not available' || phone.trim() === '') {
2097
+ // return 'Not available';
2098
+ // }
2099
+
2100
+ // const cleaned = phone.replace(/[^\d\+\(\)\-\s]/g, '');
2101
+ // const digitCount = (cleaned.match(/\d/g) || []).length;
2102
+
2103
+ // // Require at least 7 digits for a valid phone number
2104
+ // if (digitCount < 7) {
2105
+ // return 'Not available';
2106
+ // }
2107
+
2108
+ // return cleaned.trim();
2109
+ // }
2110
+
2111
+ // function validateWebsite(website) {
2112
+ // if (!website || website.toLowerCase() === 'not available' || website.trim() === '') {
2113
+ // return 'Not available';
2114
+ // }
2115
+
2116
+ // const trimmed = website.trim();
2117
+
2118
+ // // Ensure URL has proper protocol
2119
+ // if (!trimmed.startsWith('http://') && !trimmed.startsWith('https://')) {
2120
+ // // Check if it looks like a domain
2121
+ // if (trimmed.includes('.') && !trimmed.includes(' ')) {
2122
+ // return `https://${trimmed.replace(/^www\./, '')}`;
2123
+ // }
2124
+ // return 'Not available';
2125
+ // }
2126
+
2127
+ // return trimmed;
2128
+ // }
2129
+
2130
+ // function cleanStreetAddress(street) {
2131
+ // if (!street || street.toLowerCase() === 'not available' || street.trim() === '') {
2132
+ // return 'Not available';
2133
+ // }
2134
+
2135
+ // return street
2136
+ // .replace(/\s+/g, ' ')
2137
+ // .replace(/,\s*$/g, '') // Remove trailing commas
2138
+ // .trim();
2139
+ // }
2140
+
2141
+ // function cleanText(text) {
2142
+ // if (!text || text.toLowerCase() === 'not available' || text.trim() === '') {
2143
+ // return 'Not available';
2144
+ // }
2145
+
2146
+ // return text.replace(/\s+/g, ' ').trim();
2147
+ // }
2148
+
2149
+ // function cleanZipCode(zip, country) {
2150
+ // if (!zip || zip.toLowerCase() === 'not available' || zip.trim() === '') {
2151
+ // return 'Not available';
2152
+ // }
2153
+
2154
+ // const cleaned = zip.trim();
2155
+
2156
+ // // Country-specific formatting
2157
+ // switch (country) {
2158
+ // case 'US':
2159
+ // // US ZIP: 5 digits or 5-4 format
2160
+ // return cleaned.replace(/\D/g, '').replace(/^(\d{5})(\d{4})$/, '$1-$2');
2161
+ // case 'CA':
2162
+ // // Canada: A1A 1A1 format
2163
+ // return cleaned.toUpperCase().replace(/\s+/g, '');
2164
+ // case 'UK':
2165
+ // // UK: various formats, preserve as is but uppercase
2166
+ // return cleaned.toUpperCase();
2167
+ // case 'AU':
2168
+ // // Australia: 4 digits
2169
+ // return cleaned.replace(/\D/g, '');
2170
+ // default:
2171
+ // return cleaned;
2172
+ // }
2173
+ // }
2174
+
2175
+ // function cleanStateProvince(state, country) {
2176
+ // if (!state || state.toLowerCase() === 'not available' || state.trim() === '') {
2177
+ // return 'Not available';
2178
+ // }
2179
+
2180
+ // const cleaned = state.trim();
2181
+
2182
+ // // Standardize US state abbreviations
2183
+ // if (country === 'US') {
2184
+ // const stateMap = {
2185
+ // alabama: 'AL',
2186
+ // alaska: 'AK',
2187
+ // arizona: 'AZ',
2188
+ // arkansas: 'AR',
2189
+ // california: 'CA',
2190
+ // colorado: 'CO',
2191
+ // connecticut: 'CT',
2192
+ // delaware: 'DE',
2193
+ // florida: 'FL',
2194
+ // georgia: 'GA',
2195
+ // hawaii: 'HI',
2196
+ // idaho: 'ID',
2197
+ // illinois: 'IL',
2198
+ // indiana: 'IN',
2199
+ // iowa: 'IA',
2200
+ // kansas: 'KS',
2201
+ // kentucky: 'KY',
2202
+ // louisiana: 'LA',
2203
+ // maine: 'ME',
2204
+ // maryland: 'MD',
2205
+ // massachusetts: 'MA',
2206
+ // michigan: 'MI',
2207
+ // minnesota: 'MN',
2208
+ // mississippi: 'MS',
2209
+ // missouri: 'MO',
2210
+ // montana: 'MT',
2211
+ // nebraska: 'NE',
2212
+ // nevada: 'NV',
2213
+ // 'new hampshire': 'NH',
2214
+ // 'new jersey': 'NJ',
2215
+ // 'new mexico': 'NM',
2216
+ // 'new york': 'NY',
2217
+ // 'north carolina': 'NC',
2218
+ // 'north dakota': 'ND',
2219
+ // ohio: 'OH',
2220
+ // oklahoma: 'OK',
2221
+ // oregon: 'OR',
2222
+ // pennsylvania: 'PA',
2223
+ // 'rhode island': 'RI',
2224
+ // 'south carolina': 'SC',
2225
+ // 'south dakota': 'SD',
2226
+ // tennessee: 'TN',
2227
+ // texas: 'TX',
2228
+ // utah: 'UT',
2229
+ // vermont: 'VT',
2230
+ // virginia: 'VA',
2231
+ // washington: 'WA',
2232
+ // 'west virginia': 'WV',
2233
+ // wisconsin: 'WI',
2234
+ // wyoming: 'WY',
2235
+ // 'district of columbia': 'DC',
2236
+ // };
2237
+
2238
+ // const lowerState = cleaned.toLowerCase();
2239
+ // if (stateMap[lowerState]) {
2240
+ // return stateMap[lowerState];
2241
+ // }
2242
+
2243
+ // // If already 2-letter code, uppercase it
2244
+ // if (/^[A-Z]{2}$/i.test(cleaned)) {
2245
+ // return cleaned.toUpperCase();
2246
+ // }
2247
+ // }
2248
+
2249
+ // return cleaned;
2250
+ // }
2251
+
2252
+ // function cleanCountry(country) {
2253
+ // if (!country || country.toLowerCase() === 'not available' || country.trim() === '') {
2254
+ // return 'Not available';
2255
+ // }
2256
+
2257
+ // // Convert 2-letter codes to full country names for display
2258
+ // const countryMap = {
2259
+ // US: 'United States',
2260
+ // CA: 'Canada',
2261
+ // UK: 'United Kingdom',
2262
+ // GB: 'United Kingdom',
2263
+ // AU: 'Australia',
2264
+ // DE: 'Germany',
2265
+ // FR: 'France',
2266
+ // JP: 'Japan',
2267
+ // CN: 'China',
2268
+ // IN: 'India',
2269
+ // BR: 'Brazil',
2270
+ // MX: 'Mexico',
2271
+ // };
2272
+
2273
+ // const upperCountry = country.toUpperCase();
2274
+ // return countryMap[upperCountry] || upperCountry;
2275
+ // }
2276
+
2277
+ // function formatFullAddress(data) {
2278
+ // const parts = [];
2279
+
2280
+ // if (data.business_address_street && data.business_address_street !== 'Not available') {
2281
+ // parts.push(data.business_address_street);
2282
+ // }
2283
+
2284
+ // const cityStateZip = [];
2285
+ // if (data.business_address_city && data.business_address_city !== 'Not available') {
2286
+ // cityStateZip.push(data.business_address_city);
2287
+ // }
2288
+
2289
+ // if (data.business_address_state && data.business_address_state !== 'Not available') {
2290
+ // cityStateZip.push(data.business_address_state);
2291
+ // }
2292
+
2293
+ // if (data.business_address_zip && data.business_address_zip !== 'Not available') {
2294
+ // cityStateZip.push(data.business_address_zip);
2295
+ // }
2296
+
2297
+ // if (cityStateZip.length > 0) {
2298
+ // parts.push(cityStateZip.join(', '));
2299
+ // }
2300
+
2301
+ // if (data.business_address_country && data.business_address_country !== 'Not available') {
2302
+ // parts.push(data.business_address_country);
2303
+ // }
2304
+
2305
+ // return parts.length > 0 ? parts.join(', ') : 'Not available';
2306
+ // }
2307
+
2308
+ // function getRegionFromState(state, country) {
2309
+ // if (country !== 'US' || state === 'Not available') return null;
2310
+
2311
+ // const regions = {
2312
+ // Northeast: ['CT', 'ME', 'MA', 'NH', 'RI', 'VT', 'NJ', 'NY', 'PA'],
2313
+ // Midwest: ['IL', 'IN', 'MI', 'OH', 'WI', 'IA', 'KS', 'MN', 'MO', 'NE', 'ND', 'SD'],
2314
+ // South: ['DE', 'FL', 'GA', 'MD', 'NC', 'SC', 'VA', 'DC', 'WV', 'AL', 'KY', 'MS', 'TN', 'AR', 'LA', 'OK', 'TX'],
2315
+ // West: ['AZ', 'CO', 'ID', 'MT', 'NV', 'NM', 'UT', 'WY', 'AK', 'CA', 'HI', 'OR', 'WA'],
2316
+ // };
2317
+
2318
+ // for (const [region, states] of Object.entries(regions)) {
2319
+ // if (states.includes(state)) {
2320
+ // return region;
2321
+ // }
2322
+ // }
2323
+
2324
+ // return null;
2325
+ // }
2326
+
2327
+ // function getDefaultBusinessInfo(name, email, error = null) {
2328
+ // const domain = email.includes('@') ? email.split('@')[1] : '';
2329
+
2330
+ // return {
2331
+ // business_name: name,
2332
+ // business_domain: domain,
2333
+ // business_bio: 'Information not available',
2334
+ // business_size: 'unknown',
2335
+ // business_category: 'Professional Services',
2336
+ // business_sub_category: 'Business Services',
2337
+ // business_country: 'US',
2338
+ // business_phone: 'Not available',
2339
+ // business_website: 'Not available',
2340
+
2341
+ // // Address components
2342
+ // business_address_street: 'Not available',
2343
+ // business_address_city: 'Not available',
2344
+ // business_address_state: 'Not available',
2345
+ // business_address_zip: 'Not available',
2346
+ // business_address_country: 'Not available',
2347
+ // business_address_full: 'Not available',
2348
+
2349
+ // // Structured objects
2350
+ // business_category_id: null,
2351
+ // business_address: {
2352
+ // street: 'Not available',
2353
+ // city: 'Not available',
2354
+ // state: 'Not available',
2355
+ // zip: 'Not available',
2356
+ // country: 'Not available',
2357
+ // full: 'Not available',
2358
+ // coordinates: null,
2359
+ // timezone: null,
2360
+ // },
2361
+ // business_location: {
2362
+ // region: null,
2363
+ // metro_area: null,
2364
+ // is_headquarters: null,
2365
+ // },
2366
+ // error: error || 'API call failed',
2367
+ // };
2368
+ // }
2369
+
2370
+ // // Extract lists from your JSON categories array
2371
+ // const categories = [
2372
+ // {
2373
+ // id: 'ind_technology',
2374
+ // name: 'Technology',
2375
+ // sub: ['Software Development', 'AI & Machine Learning', 'Cybersecurity', 'Cloud Computing', 'IT Services', 'SaaS & Platforms', 'Hardware & Electronics'],
2376
+ // },
2377
+ // {
2378
+ // id: 'ind_marketing',
2379
+ // name: 'Marketing & Advertising',
2380
+ // sub: ['Digital Marketing', 'PPC & SEO', 'Content Creation', 'Branding', 'Social Media Management', 'Email Marketing', 'Market Research'],
2381
+ // },
2382
+ // {
2383
+ // id: 'ind_sales',
2384
+ // name: 'Sales',
2385
+ // sub: ['B2B Sales', 'B2C Sales', 'Real Estate Sales', 'Account Management', 'Lead Generation', 'Inside Sales', 'Field Sales'],
2386
+ // },
2387
+ // {
2388
+ // id: 'ind_finance',
2389
+ // name: 'Finance & Accounting',
2390
+ // sub: ['Banking', 'Investment', 'Financial Planning', 'Accounting', 'Bookkeeping', 'Insurance', 'FinTech'],
2391
+ // },
2392
+ // {
2393
+ // id: 'ind_healthcare',
2394
+ // name: 'Healthcare',
2395
+ // sub: ['Medical Clinics', 'Hospitals', 'Pharma', 'Mental Health', 'Healthcare IT', 'Home Care', 'Medical Research'],
2396
+ // },
2397
+ // {
2398
+ // id: 'ind_realestate',
2399
+ // name: 'Real Estate',
2400
+ // sub: ['Residential Real Estate', 'Commercial Real Estate', 'Property Management', 'Investment & BRRRR', 'Construction', 'Architecture', 'Interior Design'],
2401
+ // },
2402
+ // {
2403
+ // id: 'ind_ecommerce',
2404
+ // name: 'E-commerce',
2405
+ // sub: ['Online Store', 'Dropshipping', 'Amazon FBA', 'Marketplace Selling', 'Retail', 'Inventory Management', 'Fulfillment & Logistics'],
2406
+ // },
2407
+ // {
2408
+ // id: 'ind_education',
2409
+ // name: 'Education',
2410
+ // sub: ['Schools', 'Universities', 'Private Tutoring', 'Online Courses', 'EdTech', 'Training & Development'],
2411
+ // },
2412
+ // {
2413
+ // id: 'ind_hospitality',
2414
+ // name: 'Hospitality & Travel',
2415
+ // sub: ['Hotels', 'Restaurants', 'Cafes & Bars', 'Travel Agencies', 'Tourism', 'Events & Catering', 'Transportation'],
2416
+ // },
2417
+ // {
2418
+ // id: 'ind_professional',
2419
+ // name: 'Professional Services',
2420
+ // sub: ['Legal', 'Consulting', 'HR & Recruiting', 'Accounting Firms', 'Business Services', 'Management Consulting'],
2421
+ // },
2422
+ // {
2423
+ // id: 'ind_manufacturing',
2424
+ // name: 'Manufacturing',
2425
+ // sub: ['Automotive', 'Industrial', 'Textile', 'Electronics', 'Food Production', 'Machinery', 'Chemicals'],
2426
+ // },
2427
+ // {
2428
+ // id: 'ind_nonprofit',
2429
+ // name: 'Nonprofit & Government',
2430
+ // sub: ['NGOs', 'Municipality', 'Government Services', 'Public Health', 'Community Organizations', 'Education Programs'],
2431
+ // },
2432
+ // {
2433
+ // id: 'ind_media',
2434
+ // name: 'Media & Entertainment',
2435
+ // sub: ['Film & Video', 'Music', 'Publishing', 'Gaming', 'News & Journalism', 'Influencers', 'Production Studios'],
2436
+ // },
2437
+ // {
2438
+ // id: 'ind_logistics',
2439
+ // name: 'Logistics & Transportation',
2440
+ // sub: ['Shipping', 'Trucking', 'Last-Mile Delivery', 'Warehousing', 'Freight Forwarding', 'Route Optimization'],
2441
+ // },
2442
+ // {
2443
+ // id: 'ind_energy',
2444
+ // name: 'Energy & Utilities',
2445
+ // sub: ['Solar', 'Oil & Gas', 'Electricity Providers', 'Water Utilities', 'Environmental Services', 'Renewable Energy'],
2446
+ // },
2447
+ // {
2448
+ // id: 'ind_construction',
2449
+ // name: 'Construction & Trades',
2450
+ // sub: ['General Contracting', 'Roofing', 'Plumbing', 'HVAC', 'Electrical', 'Renovation', 'Engineering'],
2451
+ // },
2452
+ // {
2453
+ // id: 'ind_food',
2454
+ // name: 'Food & Beverage',
2455
+ // sub: ['Restaurants', 'Catering', 'Food Manufacturing', 'Bakeries', 'Bars & Nightlife', 'Food Delivery'],
2456
+ // },
2457
+ // {
2458
+ // id: 'ind_retail',
2459
+ // name: 'Retail',
2460
+ // sub: ['Physical Stores', 'Boutiques', 'Supermarkets', 'Consumer Goods', 'Fashion Retail', 'Home Goods'],
2461
+ // },
2462
+ // ];
2463
+ // const categoryNames = categories.map((c) => c.name);
2464
+ // const allSubCategories = categories.flatMap((c) => c.sub);
2465
+
2466
+ // const business_info_ret = await submit_chat_gpt_prompt({
2467
+ // uid,
2468
+ // prompt: `Research the company: "${name}" (${email}).
2469
+
2470
+ // REQUIRED INFORMATION:
2471
+ // 1. Company name (official name)
2472
+ // 2. Email domain name
2473
+ // 3. Professional one-sentence biography
2474
+ // 4. Industry category and sub-category
2475
+ // 5. Primary country (2-letter ISO code)
2476
+ // 6. Telephone number
2477
+ // 7. Website URL
2478
+ // 8. COMPLETE ADDRESS DETAILS:
2479
+ // - Full street address (street number, street name, suite/apt if applicable)
2480
+ // - City
2481
+ // - State/Province (use abbreviation where standard)
2482
+ // - Zip/Postal code
2483
+ // - Country
2484
+
2485
+ // ADDRESS FORMATTING EXAMPLES:
2486
+ // - Full street: "1600 Amphitheatre Parkway"
2487
+ // - City: "Mountain View"
2488
+ // - State: "CA"
2489
+ // - Zip: "94043"
2490
+ // - Country: "US"
2491
+ // - Full address: "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA"
2492
+
2493
+ // INSTRUCTIONS:
2494
+ // - Use web search to find accurate information
2495
+ // - If not found online, infer from typical patterns
2496
+ // - For unknown info, use "Not available"
2497
+ // - For US states, use 2-letter abbreviations (CA, NY, TX, etc.)
2498
+ // - For other countries, use standard regional names
2499
+
2500
+ // Be as precise and accurate as possible.`,
2501
+ // model: 'gpt-5-nano',
2502
+ // response_format: z.object({
2503
+ // business_name: z.string().describe('Official company name'),
2504
+ // business_domain: z.string().describe('Domain name from email'),
2505
+ // business_bio: z.string().describe('One-sentence professional summary'),
2506
+ // business_size: z.enum(['unknown', 'small', 'medium', 'large', 'enterprise']),
2507
+ // business_category: z.enum(categoryNames),
2508
+ // business_sub_category: z.enum(allSubCategories),
2509
+ // business_country: z.string().length(2).describe('2-letter ISO country code'),
2510
+ // business_phone: z.string().describe("Telephone number or 'Not available'"),
2511
+ // business_website: z.string().describe("Website URL or 'Not available'"),
2512
+
2513
+ // // Complete address components
2514
+ // business_address_street: z.string().describe('Full street address (number, street, suite)'),
2515
+ // business_address_city: z.string().describe('City name'),
2516
+ // business_address_state: z.string().describe('State/Province (abbreviation if standard)'),
2517
+ // business_address_zip: z.string().describe('Zip/Postal code'),
2518
+ // business_address_country: z.string().describe('Country name'),
2519
+ // business_address_full: z.string().describe('Complete formatted address'),
2520
+ // }),
2521
+ // metadata: {
2522
+ // func: 'get_business_info',
2523
+ // company_name: name,
2524
+ // company_email: email,
2525
+ // },
2526
+ // account_profile_info,
2527
+ // tools: [{ type: 'web_search_preview' }],
2528
+ // });
2529
+
2530
+ // try {
2531
+ // if (business_info_ret.code > -1) {
2532
+ // const data = typeof business_info_ret.data === 'string' ? JSON.parse(business_info_ret.data) : business_info_ret.data;
2533
+
2534
+ // // Standardize country codes to uppercase
2535
+ // if (data.business_country) data.business_country = data.business_country.toUpperCase();
2536
+ // if (data.business_address_country) {
2537
+ // data.business_address_country = data.business_address_country.toUpperCase();
2538
+ // }
2539
+
2540
+ // // Logic to attach the ID for your database
2541
+ // const matched = categories.find((c) => c.name === data.business_category);
2542
+ // data.business_category_id = matched ? matched.id : null;
2543
+
2544
+ // // Validate and clean all contact information
2545
+ // data.business_phone = validatePhoneNumber(data.business_phone);
2546
+ // data.business_website = validateWebsite(data.business_website);
2547
+
2548
+ // // Clean and standardize all address components
2549
+ // data.business_address_street = cleanStreetAddress(data.business_address_street);
2550
+ // data.business_address_city = cleanText(data.business_address_city);
2551
+ // data.business_address_zip = cleanZipCode(data.business_address_zip, data.business_country);
2552
+ // data.business_address_state = cleanStateProvince(data.business_address_state, data.business_country);
2553
+ // data.business_address_country = cleanCountry(data.business_address_country || data.business_country);
2554
+ // data.business_address_full = formatFullAddress(data);
2555
+
2556
+ // // Create a comprehensive structured address object
2557
+ // data.business_address = {
2558
+ // street: data.business_address_street,
2559
+ // city: data.business_address_city,
2560
+ // state: data.business_address_state,
2561
+ // zip: data.business_address_zip,
2562
+ // country: data.business_address_country,
2563
+ // full: data.business_address_full,
2564
+ // coordinates: null, // Can be populated later with geocoding
2565
+ // timezone: null, // Can be populated later
2566
+ // };
2567
+
2568
+ // // Generate additional useful fields
2569
+ // data.business_location = {
2570
+ // region: getRegionFromState(data.business_address_state, data.business_country),
2571
+ // metro_area: null, // Can be populated later
2572
+ // is_headquarters: null, // Can be determined from address pattern
2573
+ // };
2574
+
2575
+ // return data;
2576
+ // } else {
2577
+ // console.error('Business info API call failed:', business_info_ret);
2578
+ // return getDefaultBusinessInfo(name, email);
2579
+ // }
2580
+ // } catch (error) {
2581
+ // console.error('Error in get_business_info:', error);
2582
+ // return getDefaultBusinessInfo(name, email, error.message);
2583
+ // }
2584
+ // };
2585
+
2586
+ // export const get_person_info = async function (uid, name, email, account_profile_info, email_context = '') {
2587
+ // // ========== HELPER FUNCTIONS ==========
2588
+
2589
+ // async function hashString(str) {
2590
+ // // Simple hash for context tracking
2591
+ // const encoder = new TextEncoder();
2592
+ // const data = encoder.encode(str);
2593
+ // const hashBuffer = await crypto.subtle.digest('SHA-256', data);
2594
+ // const hashArray = Array.from(new Uint8Array(hashBuffer));
2595
+ // return hashArray
2596
+ // .map((b) => b.toString(16).padStart(2, '0'))
2597
+ // .join('')
2598
+ // .substring(0, 16);
2599
+ // }
2600
+
2601
+ // function processPersonInfo(data, originalName, originalEmail, emailContext) {
2602
+ // // Ensure basic fields are populated
2603
+ // if (!data.person_first_name || !data.person_last_name) {
2604
+ // const nameParts = originalName.trim().split(/\s+/);
2605
+ // data.person_first_name = data.person_first_name || nameParts[0] || '';
2606
+ // data.person_last_name = data.person_last_name || nameParts.slice(1).join(' ') || '';
2607
+ // }
2608
+
2609
+ // // Set full name if not provided
2610
+ // if (!data.person_full_name) {
2611
+ // data.person_full_name = `${data.person_first_name} ${data.person_last_name}`.trim();
2612
+ // }
2613
+
2614
+ // // Ensure email is set
2615
+ // data.person_email = data.person_email || originalEmail;
2616
+
2617
+ // // Process demographic information
2618
+ // data.person_age = processAge(data.person_age);
2619
+ // data.person_gender = data.person_gender || 'unknown';
2620
+ // data.person_nationality = processNationality(data.person_nationality);
2621
+
2622
+ // // Standardize location fields
2623
+ // data.person_location_city = cleanText(data.person_location_city);
2624
+ // data.person_location_state = cleanStateProvince(data.person_location_state);
2625
+ // data.person_location_country = processCountryCode(data.person_location_country);
2626
+
2627
+ // // Format full location
2628
+ // if (!data.person_location_full || data.person_location_full === 'Not available') {
2629
+ // const locationParts = [];
2630
+ // if (data.person_location_city && data.person_location_city !== 'Not available') {
2631
+ // locationParts.push(data.person_location_city);
2632
+ // }
2633
+ // if (data.person_location_state && data.person_location_state !== 'Not available') {
2634
+ // locationParts.push(data.person_location_state);
2635
+ // }
2636
+ // if (data.person_location_country && data.person_location_country !== 'Not available') {
2637
+ // locationParts.push(countryCodeToName(data.person_location_country));
2638
+ // }
2639
+ // data.person_location_full = locationParts.length > 0 ? locationParts.join(', ') : 'Not available';
2640
+ // }
2641
+
2642
+ // // Clean and validate URLs
2643
+ // data.person_linkedin = validateURL(data.person_linkedin);
2644
+ // data.person_twitter = validateURL(data.person_twitter);
2645
+ // data.person_github = validateURL(data.person_github);
2646
+ // data.person_website = validateURL(data.person_website);
2647
+
2648
+ // // Clean phone number
2649
+ // data.person_phone = validatePhoneNumber(data.person_phone);
2650
+
2651
+ // // Ensure arrays are properly formatted
2652
+ // data.person_skills = ensureArray(data.person_skills);
2653
+ // data.person_expertise = ensureArray(data.person_expertise);
2654
+ // data.person_education = ensureArray(data.person_education);
2655
+ // data.person_languages = ensureArray(data.person_languages);
2656
+ // data.person_interests = ensureArray(data.person_interests);
2657
+ // data.person_context_insights = ensureArray(data.person_context_insights);
2658
+
2659
+ // // Calculate additional metadata
2660
+ // data.person_name_initials = getInitials(data.person_first_name, data.person_last_name);
2661
+ // data.person_age_range = calculateAgeRange(data.person_age);
2662
+ // data.person_seniority_score = calculateSeniorityScore(data);
2663
+ // data.person_pronouns = getPronounsFromGender(data.person_gender);
2664
+
2665
+ // // Extract insights from email context
2666
+ // if (emailContext && !data.person_context_insights) {
2667
+ // data.person_context_insights = extractContextInsights(emailContext);
2668
+ // }
2669
+
2670
+ // // Create structured objects for easier access
2671
+ // data.person_demographics = {
2672
+ // age: data.person_age,
2673
+ // age_range: data.person_age_range,
2674
+ // gender: data.person_gender,
2675
+ // pronouns: data.person_pronouns,
2676
+ // nationality: data.person_nationality,
2677
+ // nationality_name: countryCodeToName(data.person_nationality),
2678
+ // };
2679
+
2680
+ // data.person_contact = {
2681
+ // email: data.person_email,
2682
+ // phone: data.person_phone,
2683
+ // location: {
2684
+ // city: data.person_location_city,
2685
+ // state: data.person_location_state,
2686
+ // country: data.person_location_country,
2687
+ // country_name: countryCodeToName(data.person_location_country),
2688
+ // full: data.person_location_full,
2689
+ // },
2690
+ // };
2691
+
2692
+ // data.person_professional = {
2693
+ // title: data.person_title,
2694
+ // company: data.person_company,
2695
+ // industry: data.person_industry,
2696
+ // career_level: data.person_career_level,
2697
+ // years_experience: data.person_years_experience,
2698
+ // skills: data.person_skills,
2699
+ // expertise: data.person_expertise,
2700
+ // education: data.person_education,
2701
+ // };
2702
+
2703
+ // data.person_online = {
2704
+ // linkedin: data.person_linkedin,
2705
+ // twitter: data.person_twitter,
2706
+ // github: data.person_github,
2707
+ // website: data.person_website,
2708
+ // other: data.person_social_other || [],
2709
+ // };
2710
+
2711
+ // // Add context metadata
2712
+ // data.context_analysis = {
2713
+ // has_context: !!emailContext,
2714
+ // context_length: emailContext?.length || 0,
2715
+ // extracted_insights: data.person_context_insights || [],
2716
+ // context_useful: data.person_has_context_hints || false,
2717
+ // };
2718
+
2719
+ // // Add timestamp
2720
+ // data.retrieved_at = new Date().toISOString();
2721
+
2722
+ // return data;
2723
+ // }
2724
+
2725
+ // function processAge(ageInput) {
2726
+ // if (!ageInput || ageInput === 'unknown' || ageInput === 'Not available') {
2727
+ // return 'unknown';
2728
+ // }
2729
+
2730
+ // if (typeof ageInput === 'number') {
2731
+ // return Math.max(18, Math.min(100, ageInput));
2732
+ // }
2733
+
2734
+ // if (typeof ageInput === 'string') {
2735
+ // // Parse age ranges like "30-40", "35+", "mid-30s"
2736
+ // const rangeMatch = ageInput.match(/(\d+)-(\d+)/);
2737
+ // if (rangeMatch) {
2738
+ // const avg = Math.floor((parseInt(rangeMatch[1]) + parseInt(rangeMatch[2])) / 2);
2739
+ // return avg;
2740
+ // }
2741
+
2742
+ // const numberMatch = ageInput.match(/\d+/);
2743
+ // if (numberMatch) {
2744
+ // const age = parseInt(numberMatch[0]);
2745
+ // if (age >= 18 && age <= 100) return age;
2746
+ // }
2747
+
2748
+ // // Handle textual age descriptions
2749
+ // const text = ageInput.toLowerCase();
2750
+ // if (text.includes('twent') || text.includes('20')) return 25;
2751
+ // if (text.includes('thirt') || text.includes('30')) return 35;
2752
+ // if (text.includes('fort') || text.includes('40')) return 45;
2753
+ // if (text.includes('fift') || text.includes('50')) return 55;
2754
+ // if (text.includes('sixt') || text.includes('60')) return 65;
2755
+ // }
2756
+
2757
+ // return 'unknown';
2758
+ // }
2759
+
2760
+ // function calculateAgeRange(age) {
2761
+ // if (age === 'unknown' || typeof age !== 'number') return 'Unknown';
2762
+
2763
+ // if (age < 25) return '18-24';
2764
+ // if (age < 30) return '25-29';
2765
+ // if (age < 35) return '30-34';
2766
+ // if (age < 40) return '35-39';
2767
+ // if (age < 50) return '40-49';
2768
+ // if (age < 60) return '50-59';
2769
+ // return '60+';
2770
+ // }
2771
+
2772
+ // function processNationality(nationality) {
2773
+ // if (!nationality || nationality.toLowerCase() === 'unknown' || nationality.toLowerCase() === 'not available') {
2774
+ // return 'unknown';
2775
+ // }
2776
+
2777
+ // // Convert to uppercase for country codes
2778
+ // const upper = nationality.toUpperCase();
2779
+
2780
+ // // Map common variations to ISO codes
2781
+ // const countryMap = {
2782
+ // USA: 'US',
2783
+ // 'UNITED STATES': 'US',
2784
+ // AMERICA: 'US',
2785
+ // UK: 'GB',
2786
+ // 'UNITED KINGDOM': 'GB',
2787
+ // ENGLAND: 'GB',
2788
+ // SCOTLAND: 'GB',
2789
+ // CANADA: 'CA',
2790
+ // AUSTRALIA: 'AU',
2791
+ // INDIA: 'IN',
2792
+ // GERMANY: 'DE',
2793
+ // FRANCE: 'FR',
2794
+ // CHINA: 'CN',
2795
+ // JAPAN: 'JP',
2796
+ // BRAZIL: 'BR',
2797
+ // MEXICO: 'MX',
2798
+ // SPAIN: 'ES',
2799
+ // ITALY: 'IT',
2800
+ // NETHERLANDS: 'NL',
2801
+ // SWEDEN: 'SE',
2802
+ // SWITZERLAND: 'CH',
2803
+ // 'SOUTH KOREA': 'KR',
2804
+ // RUSSIA: 'RU',
2805
+ // };
2806
+
2807
+ // if (countryMap[upper]) {
2808
+ // return countryMap[upper];
2809
+ // }
2810
+
2811
+ // // If it's already a 2-letter code, return it
2812
+ // if (/^[A-Z]{2}$/.test(upper)) {
2813
+ // return upper;
2814
+ // }
2815
+
2816
+ // return 'unknown';
2817
+ // }
2818
+
2819
+ // function processCountryCode(country) {
2820
+ // if (!country || country.toLowerCase() === 'not available') {
2821
+ // return 'unknown';
2822
+ // }
2823
+
2824
+ // return processNationality(country);
2825
+ // }
2826
+
2827
+ // function countryCodeToName(code) {
2828
+ // if (!code || code === 'unknown') return 'Unknown';
2829
+
2830
+ // const countryNames = {
2831
+ // US: 'United States',
2832
+ // GB: 'United Kingdom',
2833
+ // CA: 'Canada',
2834
+ // AU: 'Australia',
2835
+ // DE: 'Germany',
2836
+ // FR: 'France',
2837
+ // JP: 'Japan',
2838
+ // CN: 'China',
2839
+ // IN: 'India',
2840
+ // BR: 'Brazil',
2841
+ // MX: 'Mexico',
2842
+ // ES: 'Spain',
2843
+ // IT: 'Italy',
2844
+ // NL: 'Netherlands',
2845
+ // SE: 'Sweden',
2846
+ // CH: 'Switzerland',
2847
+ // KR: 'South Korea',
2848
+ // RU: 'Russia',
2849
+ // };
2850
+
2851
+ // return countryNames[code] || code;
2852
+ // }
2853
+
2854
+ // function getPronounsFromGender(gender) {
2855
+ // switch (gender) {
2856
+ // case 'male':
2857
+ // return ['he/him', 'his'];
2858
+ // case 'female':
2859
+ // return ['she/her', 'hers'];
2860
+ // case 'non-binary':
2861
+ // return ['they/them', 'theirs'];
2862
+ // default:
2863
+ // return ['unknown'];
2864
+ // }
2865
+ // }
2866
+
2867
+ // function extractContextInsights(emailContext) {
2868
+ // if (!emailContext) return [];
2869
+
2870
+ // const insights = [];
2871
+ // const context = emailContext.toLowerCase();
2872
+
2873
+ // // Extract potential job role hints
2874
+ // const rolePatterns = {
2875
+ // manager: ['manage', 'supervise', 'team lead', 'department head'],
2876
+ // engineer: ['engineer', 'developer', 'programmer', 'software'],
2877
+ // sales: ['sales', 'account executive', 'business development'],
2878
+ // marketing: ['marketing', 'campaign', 'brand', 'social media'],
2879
+ // executive: ['ceo', 'cto', 'cfo', 'director', 'vp', 'vice president'],
2880
+ // };
2881
+
2882
+ // for (const [role, patterns] of Object.entries(rolePatterns)) {
2883
+ // if (patterns.some((pattern) => context.includes(pattern))) {
2884
+ // insights.push(`Possible ${role} role indicated in email`);
2885
+ // }
2886
+ // }
2887
+
2888
+ // // Extract company hints
2889
+ // const companyMatch = context.match(/(?:at|from|of)\s+([A-Z][A-Za-z0-9\s&]+)(?:\s|$)/);
2890
+ // if (companyMatch && companyMatch[1].length > 2) {
2891
+ // insights.push(`Mentioned company/organization: ${companyMatch[1].trim()}`);
2892
+ // }
2893
+
2894
+ // // Extract project/technology hints
2895
+ // const techMatch = context.match(/(?:using|with|built\s+in)\s+([A-Za-z0-9\s+#]+)(?:\s|$)/);
2896
+ // if (techMatch) {
2897
+ // insights.push(`Technology mentioned: ${techMatch[1].trim()}`);
2898
+ // }
2899
+
2900
+ // // Extract urgency/priority
2901
+ // if (context.includes('urgent') || context.includes('asap') || context.includes('immediately')) {
2902
+ // insights.push('Email suggests urgency or time sensitivity');
2903
+ // }
2904
+
2905
+ // // Extract tone
2906
+ // if (context.includes('thank you') || context.includes('appreciate') || context.includes('grateful')) {
2907
+ // insights.push('Email shows appreciative/grateful tone');
2908
+ // }
2909
+
2910
+ // return insights.slice(0, 5); // Limit to 5 insights
2911
+ // }
2912
+
2913
+ // // Existing helper functions (kept from previous version)
2914
+ // function validateURL(url) {
2915
+ // /* ... same as before ... */
2916
+ // }
2917
+ // function validatePhoneNumber(phone) {
2918
+ // /* ... same as before ... */
2919
+ // }
2920
+ // function cleanText(text) {
2921
+ // /* ... same as before ... */
2922
+ // }
2923
+ // function cleanStateProvince(state) {
2924
+ // /* ... same as before ... */
2925
+ // }
2926
+ // function ensureArray(value) {
2927
+ // /* ... same as before ... */
2928
+ // }
2929
+ // function getInitials(firstName, lastName) {
2930
+ // /* ... same as before ... */
2931
+ // }
2932
+ // function calculateSeniorityScore(data) {
2933
+ // /* ... same as before ... */
2934
+ // }
2935
+
2936
+ // function getDefaultPersonInfo(name, email, emailContext = '', error = null) {
2937
+ // const nameParts = name.trim().split(/\s+/);
2938
+ // const firstName = nameParts[0] || '';
2939
+ // const lastName = nameParts.slice(1).join(' ') || '';
2940
+ // const domain = email.includes('@') ? email.split('@')[1] : '';
2941
+ // const companyGuess = domain
2942
+ // .replace(/\..*$/, '')
2943
+ // .replace(/[^a-z]/gi, ' ')
2944
+ // .replace(/\b\w/g, (l) => l.toUpperCase());
2945
+
2946
+ // // Extract basic insights from email context
2947
+ // const contextInsights = emailContext ? extractContextInsights(emailContext) : [];
2948
+
2949
+ // return {
2950
+ // // Basic Information
2951
+ // person_full_name: name,
2952
+ // person_first_name: firstName,
2953
+ // person_last_name: lastName,
2954
+ // person_middle_name: '',
2955
+ // person_preferred_name: '',
2956
+
2957
+ // // Demographic Information
2958
+ // person_age: 'unknown',
2959
+ // person_gender: 'unknown',
2960
+ // person_nationality: 'unknown',
2961
+ // person_age_range: 'Unknown',
2962
+ // person_pronouns: ['unknown'],
2963
+
2964
+ // // Professional Information
2965
+ // person_title: 'Professional',
2966
+ // person_company: companyGuess || 'Unknown',
2967
+ // person_industry: 'Technology',
2968
+ // person_bio: 'Information not available',
2969
+
2970
+ // // Location
2971
+ // person_location_city: 'Not available',
2972
+ // person_location_state: 'Not available',
2973
+ // person_location_country: 'unknown',
2974
+ // person_location_full: 'Not available',
2975
+
2976
+ // // Contact Information
2977
+ // person_phone: 'Not available',
2978
+ // person_email: email,
2979
+ // person_email_alternate: '',
2980
+
2981
+ // // Education
2982
+ // person_education: [],
2983
+ // person_education_highest: 'Not available',
2984
+
2985
+ // // Professional Details
2986
+ // person_skills: [],
2987
+ // person_expertise: [],
2988
+ // person_career_level: 'unknown',
2989
+ // person_years_experience: 0,
2990
+
2991
+ // // Social & Online Presence
2992
+ // person_linkedin: 'Not available',
2993
+ // person_twitter: 'Not available',
2994
+ // person_github: 'Not available',
2995
+ // person_website: 'Not available',
2996
+ // person_social_other: [],
2997
+
2998
+ // // Additional Information
2999
+ // person_languages: ['English'],
3000
+ // person_interests: [],
3001
+ // person_achievements: [],
3002
+ // person_current_projects: [],
3003
+ // person_context_insights: contextInsights,
3004
+
3005
+ // // Metadata
3006
+ // person_available_for_opportunities: false,
3007
+ // person_last_updated: new Date().toISOString(),
3008
+ // person_source_confidence: 0,
3009
+ // person_has_context_hints: contextInsights.length > 0,
3010
+
3011
+ // // Processed fields
3012
+ // person_name_initials: getInitials(firstName, lastName),
3013
+ // person_seniority_score: 0,
3014
+
3015
+ // // Structured objects
3016
+ // person_demographics: {
3017
+ // age: 'unknown',
3018
+ // age_range: 'Unknown',
3019
+ // gender: 'unknown',
3020
+ // pronouns: ['unknown'],
3021
+ // nationality: 'unknown',
3022
+ // nationality_name: 'Unknown',
3023
+ // },
3024
+
3025
+ // person_contact: {
3026
+ // email: email,
3027
+ // phone: 'Not available',
3028
+ // location: {
3029
+ // city: 'Not available',
3030
+ // state: 'Not available',
3031
+ // country: 'unknown',
3032
+ // country_name: 'Unknown',
3033
+ // full: 'Not available',
3034
+ // },
3035
+ // },
3036
+
3037
+ // person_professional: {
3038
+ // title: 'Professional',
3039
+ // company: companyGuess || 'Unknown',
3040
+ // industry: 'Technology',
3041
+ // career_level: 'unknown',
3042
+ // years_experience: 0,
3043
+ // skills: [],
3044
+ // expertise: [],
3045
+ // education: [],
3046
+ // },
3047
+
3048
+ // person_online: {
3049
+ // linkedin: 'Not available',
3050
+ // twitter: 'Not available',
3051
+ // github: 'Not available',
3052
+ // website: 'Not available',
3053
+ // other: [],
3054
+ // },
3055
+
3056
+ // context_analysis: {
3057
+ // has_context: !!emailContext,
3058
+ // context_length: emailContext?.length || 0,
3059
+ // extracted_insights: contextInsights,
3060
+ // context_useful: contextInsights.length > 0,
3061
+ // },
3062
+
3063
+ // retrieved_at: new Date().toISOString(),
3064
+ // error: error || 'API call failed',
3065
+ // };
3066
+ // }
3067
+
3068
+ // // Build context-aware prompt
3069
+ // let context_prompt = `Research the person: "${name}" (${email}).`;
3070
+
3071
+ // if (email_context) {
3072
+ // context_prompt += `\n\nEMAIL CONTEXT PROVIDED:\n"${email_context.substring(0, 500)}${email_context.length > 500 ? '...' : ''}"`;
3073
+ // }
3074
+
3075
+ // context_prompt += `
3076
+
3077
+ // REQUIRED PERSON INFORMATION:
3078
+ // 1. Full name (first, middle, last)
3079
+ // 2. Professional title/role
3080
+ // 3. Company/organization they work for
3081
+ // 4. Industry/field they work in
3082
+ // 5. Location (city, state, country)
3083
+ // 6. Professional biography (1-2 sentences)
3084
+ // 7. Education background
3085
+ // 8. Professional skills/expertise
3086
+ // 9. Social media profiles (LinkedIn, Twitter, GitHub, etc.)
3087
+ // 10. Personal website or portfolio
3088
+
3089
+ // DEMOGRAPHIC INFORMATION:
3090
+ // 11. Estimated age (based on career, education, and public information)
3091
+ // 12. Gender (based on name, pronouns in content, or public profiles)
3092
+ // 13. Nationality/country of origin (if discernible) (based on name, pronouns in content, or public profiles)
3093
+
3094
+ // CONTACT INFORMATION:
3095
+ // 14. Phone number (if available)
3096
+ // 15. Alternate email addresses (if available)
3097
+ // 16. Physical address (if available and appropriate)
3098
+
3099
+ // ADDITIONAL INSIGHTS:
3100
+ // 17. Career level (entry, mid, senior, executive, etc.)
3101
+ // 18. Years of experience
3102
+ // 19. Notable achievements/awards
3103
+ // 20. Languages spoken
3104
+ // 21. Professional interests
3105
+ // 22. Current projects
3106
+ // 23. Availability for opportunities
3107
+
3108
+ // INSTRUCTIONS:
3109
+ // - Use web search to find accurate, public information
3110
+ // - Use email context provided to infer additional details
3111
+ // - Respect privacy - only include publicly available information
3112
+ // - For age: provide numeric estimate or range (e.g., 35, 30-40, unknown)
3113
+ // - For gender: use male/female/non-binary/unknown based on available cues
3114
+ // - For country: use 2-letter ISO code (e.g., US, IN, UK)
3115
+ // - If information is not available, use "Not available" or appropriate defaults
3116
+ // - For location, use standard formats (e.g., "San Francisco, CA, USA")
3117
+ // - For social media, provide full URLs when available
3118
+ // - Focus on professional information suitable for business networking
3119
+
3120
+ // Be thorough but respectful of privacy boundaries.`;
3121
+
3122
+ // const person_info_ret = await submit_chat_gpt_prompt({
3123
+ // uid,
3124
+ // prompt: context_prompt,
3125
+ // model: 'gpt-5-nano',
3126
+ // response_format: z.object({
3127
+ // // Basic Information
3128
+ // person_full_name: z.string().describe("Person's full name"),
3129
+ // person_first_name: z.string().describe('First name'),
3130
+ // person_last_name: z.string().describe('Last name'),
3131
+ // person_middle_name: z.string().optional().nullable().describe('Middle name if available'),
3132
+ // person_preferred_name: z.string().optional().nullable().describe('Preferred/nickname if different'),
3133
+
3134
+ // // Demographic Information
3135
+ // person_age: z.union([z.number().int().min(18).max(100), z.string().describe("Age range or 'unknown'")]).describe('find age base on the name Estimated age or range'),
3136
+ // person_gender: z.enum(['male', 'female']).describe('find Gender based on the name'),
3137
+ // person_nationality: z.string().describe('find nationality based on the name Country of origin/nationality (2-letter ISO code)'),
3138
+
3139
+ // // Professional Information
3140
+ // person_title: z.string().describe('Professional title/role'),
3141
+ // person_company: z.string().describe('Current company/organization'),
3142
+ // person_industry: z.string().describe('Primary industry/field'),
3143
+ // person_bio: z.string().describe('Professional biography (1-2 sentences)'),
3144
+
3145
+ // // Location
3146
+ // person_location_city: z.string().describe('City of residence/work'),
3147
+ // person_location_state: z.string().describe('State/province'),
3148
+ // person_location_country: z.string().describe('Country (2-letter ISO code)'),
3149
+ // person_location_full: z.string().describe('Full location string'),
3150
+
3151
+ // // Contact Information
3152
+ // person_phone: z.string().describe("Phone number or 'Not available'"),
3153
+ // person_email: z.string().describe('Primary email address'),
3154
+ // person_email_alternate: z.string().optional().nullable().describe('Alternate email if available'),
3155
+
3156
+ // // Education
3157
+ // person_education: z.array(z.string()).describe('Array of educational institutions/degrees'),
3158
+ // person_education_highest: z.string().describe('Highest degree obtained'),
3159
+
3160
+ // // Professional Details
3161
+ // person_skills: z.array(z.string()).describe('Array of professional skills'),
3162
+ // person_expertise: z.array(z.string()).describe('Areas of expertise'),
3163
+ // person_career_level: z.enum(['entry', 'mid', 'senior', 'lead', 'manager', 'director', 'executive', 'founder', 'unknown']),
3164
+ // person_years_experience: z.number().int().min(0).max(60).describe('Years of professional experience'),
3165
+
3166
+ // // Social & Online Presence
3167
+ // person_linkedin: z.string().describe("LinkedIn profile URL or 'Not available'"),
3168
+ // person_twitter: z.string().describe("Twitter/X profile URL or 'Not available'"),
3169
+ // person_github: z.string().describe("GitHub profile URL or 'Not available'"),
3170
+ // person_website: z.string().describe("Personal website/portfolio or 'Not available'"),
3171
+ // person_social_other: z.array(z.string()).optional().nullable().describe('Other social media profiles'),
3172
+
3173
+ // // Additional Information
3174
+ // person_languages: z.array(z.string()).describe('Languages spoken'),
3175
+ // person_interests: z.array(z.string()).describe('Professional/personal interests'),
3176
+ // person_achievements: z.array(z.string()).optional().nullable().describe('Notable achievements/awards'),
3177
+ // person_current_projects: z.array(z.string()).optional().nullable().describe('Current projects'),
3178
+
3179
+ // // Context Extracted Information
3180
+ // person_context_insights: z.array(z.string()).optional().nullable().describe('Insights extracted from provided email context'),
3181
+
3182
+ // // Metadata
3183
+ // person_available_for_opportunities: z.boolean().describe('Open to new opportunities'),
3184
+ // person_last_updated: z.string().describe('Date information was last verified'),
3185
+ // person_source_confidence: z.number().min(0).max(100).describe('Confidence score for information accuracy'),
3186
+ // person_has_context_hints: z.boolean().describe('Whether email context provided useful hints'),
3187
+ // }),
3188
+ // metadata: {
3189
+ // func: 'get_person_info',
3190
+ // person_name: name,
3191
+ // person_email: email,
3192
+ // has_email_context: !!email_context,
3193
+ // email_context_length: email_context?.length || 0,
3194
+ // context_hash: email_context ? await hashString(email_context.substring(0, 200)) : null,
3195
+ // },
3196
+ // account_profile_info,
3197
+ // tools: [{ type: 'web_search_preview' }],
3198
+ // });
3199
+
3200
+ // try {
3201
+ // if (person_info_ret.code > -1) {
3202
+ // const data = typeof person_info_ret.data === 'string' ? JSON.parse(person_info_ret.data) : person_info_ret.data;
3203
+
3204
+ // // Process and enhance the data
3205
+ // const processedData = processPersonInfo(data, name, email, email_context);
3206
+
3207
+ // return processedData;
3208
+ // } else {
3209
+ // console.error('Person info API call failed:', person_info_ret);
3210
+ // return getDefaultPersonInfo(name, email, email_context);
3211
+ // }
3212
+ // } catch (error) {
3213
+ // console.error('Error in get_person_info:', error);
3214
+ // return getDefaultPersonInfo(name, email, email_context, error.message);
3215
+ // }
3216
+ // };
3217
+
3218
+ // export const analyze_email_account_type = async function (uid, name, email, account_profile_info, email_context = '') {
3219
+ // // ========== HELPER FUNCTIONS ==========
3220
+
3221
+ // function enhanceEmailAnalysis(data, name, email, emailContext) {
3222
+ // const domain = email.split('@')[1] || '';
3223
+ // const localPart = email.split('@')[0] || '';
3224
+ // const nameParts = name.toLowerCase().split(/\s+/);
3225
+ // const firstName = nameParts[0] || '';
3226
+ // const lastName = nameParts.slice(-1)[0] || '';
3227
+
3228
+ // // Enhanced business company detection
3229
+ // if (data.account_type === 'business' && !data.business_company_name) {
3230
+ // data.business_company_name = inferCompanyFromDomain(domain);
3231
+ // }
3232
+
3233
+ // // Enhanced person detection
3234
+ // if (!data.is_real_person) {
3235
+ // data.is_real_person = detectRealPerson(localPart, name, domain);
3236
+ // }
3237
+
3238
+ // if (!data.person_name_in_email) {
3239
+ // data.person_name_in_email = checkNameInEmail(localPart, firstName, lastName);
3240
+ // }
3241
+
3242
+ // // Enhanced pattern analysis
3243
+ // if (data.email_pattern === 'unknown') {
3244
+ // data.email_pattern = analyzeEmailPattern(localPart, domain);
3245
+ // }
3246
+
3247
+ // // Enhanced personal provider detection
3248
+ // if (data.account_type === 'personal' && !data.personal_account_provider) {
3249
+ // data.personal_account_provider = identifyPersonalProvider(domain);
3250
+ // }
3251
+
3252
+ // // Enhanced risk assessment
3253
+ // if (data.spam_risk_level === 'unknown') {
3254
+ // data.spam_risk_level = assessSpamRisk(localPart, domain, data.account_type);
3255
+ // }
3256
+
3257
+ // // Enhanced activity assessment
3258
+ // if (!data.is_likely_active) {
3259
+ // data.is_likely_active = assessEmailActivity(localPart, domain, data.account_type, data.business_account_category);
3260
+ // }
3261
+
3262
+ // // Add domain analysis
3263
+ // data.domain_analysis = {
3264
+ // domain: domain,
3265
+ // is_public_provider: isPublicEmailProvider(domain),
3266
+ // is_custom_domain: isCustomDomain(domain),
3267
+ // is_free_email: isFreeEmailDomain(domain),
3268
+ // is_education: isEducationDomain(domain),
3269
+ // is_government: isGovernmentDomain(domain),
3270
+ // tld: domain.split('.').pop() || '',
3271
+ // };
3272
+
3273
+ // // Add name-email correlation score
3274
+ // data.name_email_correlation = calculateNameEmailCorrelation(localPart, firstName, lastName);
3275
+
3276
+ // // Add professional score
3277
+ // data.professional_score = calculateProfessionalScore(data);
3278
+
3279
+ // // Add structured recommendations
3280
+ // data.recommendations = generateRecommendations(data);
3281
+
3282
+ // // Add verification suggestions
3283
+ // data.verification_suggestions = generateVerificationSuggestions(data, emailContext);
3284
+
3285
+ // // Add timestamp
3286
+ // data.analysis_timestamp = data.analysis_timestamp || new Date().toISOString();
3287
+
3288
+ // return data;
3289
+ // }
3290
+
3291
+ // function inferCompanyFromDomain(domain) {
3292
+ // if (!domain) return 'Unknown';
3293
+
3294
+ // // Remove common TLDs and public providers
3295
+ // const baseDomain = domain.replace(/\.(com|org|net|co|io|ai|tech|app|dev)$/, '');
3296
+
3297
+ // // Remove common subdomains
3298
+ // const cleanDomain = baseDomain.replace(/^(mail\.|email\.|webmail\.|smtp\.|mx\.|imap\.)/, '').replace(/\.(com|org|net)$/, '');
3299
+
3300
+ // // Convert to readable company name
3301
+ // const companyName = cleanDomain
3302
+ // .split(/[\.\-]/)
3303
+ // .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
3304
+ // .join(' ');
3305
+
3306
+ // return companyName || 'Unknown';
3307
+ // }
3308
+
3309
+ // function detectRealPerson(localPart, name, domain) {
3310
+ // // Check for generic email addresses
3311
+ // const genericPatterns = [
3312
+ // 'info',
3313
+ // 'support',
3314
+ // 'sales',
3315
+ // 'contact',
3316
+ // 'hello',
3317
+ // 'noreply',
3318
+ // 'no-reply',
3319
+ // 'admin',
3320
+ // 'administrator',
3321
+ // 'webmaster',
3322
+ // 'postmaster',
3323
+ // 'hostmaster',
3324
+ // 'abuse',
3325
+ // 'security',
3326
+ // 'billing',
3327
+ // 'accounts',
3328
+ // 'finance',
3329
+ // 'hr',
3330
+ // 'humanresources',
3331
+ // 'marketing',
3332
+ // 'pr',
3333
+ // 'press',
3334
+ // 'media',
3335
+ // 'legal',
3336
+ // 'it',
3337
+ // 'techsupport',
3338
+ // 'help',
3339
+ // 'service',
3340
+ // 'customerservice',
3341
+ // 'feedback',
3342
+ // 'inquiries',
3343
+ // ];
3344
+
3345
+ // const localLower = localPart.toLowerCase();
3346
+
3347
+ // // If it matches generic patterns, likely not a real person
3348
+ // if (genericPatterns.some((pattern) => localLower === pattern || localLower.startsWith(pattern + '.') || localLower.endsWith('.' + pattern))) {
3349
+ // return false;
3350
+ // }
3351
+
3352
+ // // Check for role-based patterns
3353
+ // const rolePatterns = ['ceo', 'cto', 'cfo', 'coo', 'cm', 'director', 'manager', 'head', 'lead', 'senior', 'junior', 'associate', 'analyst', 'engineer', 'developer', 'designer', 'architect', 'consultant', 'advisor'];
3354
+
3355
+ // // If contains role patterns but not name, might be generic
3356
+ // const hasRolePattern = rolePatterns.some((role) => localLower.includes(role));
3357
+ // const hasNameElements = checkNameInEmail(localPart, name.toLowerCase().split(' ')[0], name.toLowerCase().split(' ').slice(-1)[0]);
3358
+
3359
+ // if (hasRolePattern && !hasNameElements) {
3360
+ // return false;
3361
+ // }
3362
+
3363
+ // // Check for numeric-only or random strings
3364
+ // if (/^\d+$/.test(localPart) || /^[a-f0-9]{32}$/.test(localPart)) {
3365
+ // return false;
3366
+ // }
3367
+
3368
+ // // Check for obvious spam patterns
3369
+ // if (localLower.includes('spam') || localLower.includes('bot') || localLower.includes('test')) {
3370
+ // return false;
3371
+ // }
3372
+
3373
+ // return true;
3374
+ // }
3375
+
3376
+ // function checkNameInEmail(localPart, firstName, lastName) {
3377
+ // if (!firstName && !lastName) return false;
3378
+
3379
+ // const localLower = localPart.toLowerCase();
3380
+ // const firstLower = firstName.toLowerCase();
3381
+ // const lastLower = lastName.toLowerCase();
3382
+
3383
+ // // Check various name patterns
3384
+ // const patterns = [
3385
+ // `${firstLower}.${lastLower}`, // john.doe
3386
+ // `${firstLower}${lastLower}`, // johndoe
3387
+ // `${firstLower.charAt(0)}${lastLower}`, // jdoe
3388
+ // `${firstLower}_${lastLower}`, // john_doe
3389
+ // `${firstLower}-${lastLower}`, // john-doe
3390
+ // `${lastLower}.${firstLower}`, // doe.john
3391
+ // `${firstLower.charAt(0)}.${lastLower}`, // j.doe
3392
+ // `${lastLower}${firstLower}`, // doejohn
3393
+ // `${firstLower}`, // john
3394
+ // `${lastLower}`, // doe
3395
+ // ];
3396
+
3397
+ // return patterns.some((pattern) => localLower === pattern || localLower.startsWith(pattern + '.') || localLower.includes('.' + pattern));
3398
+ // }
3399
+
3400
+ // function analyzeEmailPattern(localPart, domain) {
3401
+ // const localLower = localPart.toLowerCase();
3402
+
3403
+ // // Common business patterns
3404
+ // if (/^[a-z]+\.[a-z]+$/.test(localLower)) return 'first.last@company.com';
3405
+ // if (/^[a-z]+[a-z]+$/.test(localLower) && localLower.length > 5) return 'firstlast@company.com';
3406
+ // if (/^[a-z]\.[a-z]+$/.test(localLower)) return 'f.last@company.com';
3407
+ // if (/^[a-z][a-z]+$/.test(localLower) && localLower.length <= 5) return 'flast@company.com';
3408
+ // if (/^[a-z]+$/.test(localLower) && localLower.length <= 8) return 'first@company.com';
3409
+ // if (/^[a-z]+\.[a-z]+\.[a-z]+$/.test(localLower)) return 'first.m.last@company.com';
3410
+
3411
+ // // Generic patterns
3412
+ // if (/^(info|support|sales|contact|hello)$/.test(localLower)) return 'role@company.com';
3413
+ // if (/^(hr|finance|marketing|it|legal)$/.test(localLower)) return 'department@company.com';
3414
+
3415
+ // // Personal patterns
3416
+ // if (isPublicEmailProvider(domain)) {
3417
+ // if (/^[a-z]+\.[a-z]+$/.test(localLower)) return 'first.last@domain.com';
3418
+ // if (/^[a-z]+[0-9]+$/.test(localLower)) return 'personal@provider.com';
3419
+ // return 'custom@personal.com';
3420
+ // }
3421
+
3422
+ // return 'unknown';
3423
+ // }
3424
+
3425
+ // function identifyPersonalProvider(domain) {
3426
+ // const providers = {
3427
+ // 'gmail.com': 'Google Gmail',
3428
+ // 'googlemail.com': 'Google Gmail',
3429
+ // 'outlook.com': 'Microsoft Outlook',
3430
+ // 'hotmail.com': 'Microsoft Hotmail',
3431
+ // 'live.com': 'Microsoft Live',
3432
+ // 'yahoo.com': 'Yahoo Mail',
3433
+ // 'ymail.com': 'Yahoo Mail',
3434
+ // 'aol.com': 'AOL Mail',
3435
+ // 'icloud.com': 'Apple iCloud',
3436
+ // 'me.com': 'Apple iCloud',
3437
+ // 'mac.com': 'Apple iCloud',
3438
+ // 'protonmail.com': 'ProtonMail',
3439
+ // 'proton.me': 'ProtonMail',
3440
+ // 'zoho.com': 'Zoho Mail',
3441
+ // 'yandex.com': 'Yandex Mail',
3442
+ // 'mail.com': 'Mail.com',
3443
+ // 'gmx.com': 'GMX Mail',
3444
+ // };
3445
+
3446
+ // return providers[domain.toLowerCase()] || 'Custom/Unknown';
3447
+ // }
3448
+
3449
+ // function isPublicEmailProvider(domain) {
3450
+ // const publicProviders = ['gmail.com', 'googlemail.com', 'outlook.com', 'hotmail.com', 'live.com', 'yahoo.com', 'ymail.com', 'aol.com', 'icloud.com', 'me.com', 'mac.com', 'protonmail.com', 'proton.me', 'zoho.com', 'yandex.com', 'mail.com', 'gmx.com'];
3451
+
3452
+ // return publicProviders.includes(domain.toLowerCase());
3453
+ // }
3454
+
3455
+ // function isFreeEmailDomain(domain) {
3456
+ // const freeDomains = ['gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com', 'aol.com', 'mail.com', 'gmx.com', 'yandex.com', 'zoho.com'];
3457
+
3458
+ // return freeDomains.includes(domain.toLowerCase());
3459
+ // }
3460
+
3461
+ // function isCustomDomain(domain) {
3462
+ // const publicProviders = ['gmail.com', 'googlemail.com', 'outlook.com', 'hotmail.com', 'live.com', 'yahoo.com', 'ymail.com', 'aol.com', 'icloud.com', 'me.com', 'mac.com', 'protonmail.com', 'proton.me', 'zoho.com', 'yandex.com', 'mail.com', 'gmx.com', 'edu', 'gov', 'mil', 'org', 'net'];
3463
+
3464
+ // return !publicProviders.some((provider) => domain.toLowerCase().includes(provider));
3465
+ // }
3466
+
3467
+ // function isEducationDomain(domain) {
3468
+ // return domain.toLowerCase().endsWith('.edu') || domain.toLowerCase().includes('.ac.');
3469
+ // }
3470
+
3471
+ // function isGovernmentDomain(domain) {
3472
+ // return domain.toLowerCase().endsWith('.gov') || domain.toLowerCase().endsWith('.mil');
3473
+ // }
3474
+
3475
+ // function assessSpamRisk(localPart, domain, accountType) {
3476
+ // const localLower = localPart.toLowerCase();
3477
+
3478
+ // // High risk indicators
3479
+ // if (localLower.includes('spam') || localLower.includes('bot')) return 'high';
3480
+ // if (/^[a-f0-9]{32}$/.test(localLower)) return 'high'; // MD5 hash-like
3481
+ // if (/^\d+$/.test(localLower)) return 'high'; // Numbers only
3482
+ // if (localLower.includes('temp') || localLower.includes('throwaway')) return 'high';
3483
+
3484
+ // // Medium risk indicators
3485
+ // if (localLower.includes('test') || localLower.includes('demo')) return 'medium';
3486
+ // if (accountType === 'personal' && localLower.includes('+')) return 'medium'; // Plus addressing
3487
+
3488
+ // // Check disposable email domains
3489
+ // if (isDisposableDomain(domain)) return 'high';
3490
+
3491
+ // return 'low';
3492
+ // }
3493
+
3494
+ // function isDisposableDomain(domain) {
3495
+ // // Common disposable/temporary email domains
3496
+ // const disposableDomains = ['tempmail.com', 'mailinator.com', 'guerrillamail.com', '10minutemail.com', 'yopmail.com', 'trashmail.com', 'dispostable.com', 'fakeinbox.com', 'throwawaymail.com', 'temp-mail.org'];
3497
+
3498
+ // return disposableDomains.some((d) => domain.toLowerCase().includes(d));
3499
+ // }
3500
+
3501
+ // function assessEmailActivity(localPart, domain, accountType, businessCategory) {
3502
+ // // Generic/role emails are usually monitored
3503
+ // if (accountType === 'business' && ['generic_role', 'department', 'catch_all'].includes(businessCategory)) {
3504
+ // return true;
3505
+ // }
3506
+
3507
+ // // Personal emails with name patterns are likely active
3508
+ // if (accountType === 'personal' && /^[a-z]+\.[a-z]+$/.test(localPart.toLowerCase())) {
3509
+ // return true;
3510
+ // }
3511
+
3512
+ // // Education and government emails are usually active
3513
+ // if (isEducationDomain(domain) || isGovernmentDomain(domain)) {
3514
+ // return true;
3515
+ // }
3516
+
3517
+ // // Disposable domains are usually inactive after short period
3518
+ // if (isDisposableDomain(domain)) {
3519
+ // return false;
3520
+ // }
3521
+
3522
+ // // Default assumption
3523
+ // return true;
3524
+ // }
3525
+
3526
+ // function calculateNameEmailCorrelation(localPart, firstName, lastName) {
3527
+ // if (!firstName && !lastName) return 0;
3528
+
3529
+ // let score = 0;
3530
+ // const localLower = localPart.toLowerCase();
3531
+ // const firstLower = firstName.toLowerCase();
3532
+ // const lastLower = lastName.toLowerCase();
3533
+
3534
+ // // Exact name patterns
3535
+ // if (localLower === `${firstLower}.${lastLower}`) score += 40;
3536
+ // if (localLower === `${firstLower}${lastLower}`) score += 35;
3537
+ // if (localLower === `${firstLower.charAt(0)}${lastLower}`) score += 30;
3538
+ // if (localLower === `${firstLower}_${lastLower}`) score += 25;
3539
+
3540
+ // // Partial matches
3541
+ // if (localLower.includes(firstLower)) score += 15;
3542
+ // if (localLower.includes(lastLower)) score += 15;
3543
+
3544
+ // // Initial matches
3545
+ // if (localLower.startsWith(firstLower.charAt(0))) score += 10;
3546
+
3547
+ // // Length consideration (shorter emails with names are better)
3548
+ // if (localLower.length <= 20) score += 5;
3549
+
3550
+ // return Math.min(score, 100);
3551
+ // }
3552
+
3553
+ // function calculateProfessionalScore(data) {
3554
+ // let score = 50; // Base score
3555
+
3556
+ // // Account type weights
3557
+ // if (data.account_type === 'business') score += 30;
3558
+ // else if (data.account_type === 'personal') score += 10;
3559
+
3560
+ // // Real person bonus
3561
+ // if (data.is_real_person) score += 20;
3562
+
3563
+ // // Active email bonus
3564
+ // if (data.is_likely_active) score += 15;
3565
+
3566
+ // // Low spam risk bonus
3567
+ // if (data.spam_risk_level === 'low') score += 10;
3568
+ // else if (data.spam_risk_level === 'high') score -= 20;
3569
+
3570
+ // // Name-email correlation bonus
3571
+ // score += (data.name_email_correlation / 100) * 20;
3572
+
3573
+ // // Business category bonus
3574
+ // if (data.business_account_category === 'personal_employee') score += 15;
3575
+
3576
+ // return Math.max(0, Math.min(100, score));
3577
+ // }
3578
+
3579
+ // function generateRecommendations(data) {
3580
+ // const recommendations = [];
3581
+
3582
+ // if (data.account_type === 'business' && data.is_real_person) {
3583
+ // if (data.business_account_category === 'personal_employee') {
3584
+ // recommendations.push('Ideal for direct professional outreach');
3585
+ // recommendations.push('Suitable for sales, recruitment, and partnership discussions');
3586
+ // } else if (data.business_account_category === 'department') {
3587
+ // recommendations.push('Best for department-specific inquiries');
3588
+ // recommendations.push('Use for customer support or service requests');
3589
+ // }
3590
+ // } else if (data.account_type === 'personal') {
3591
+ // recommendations.push('Suitable for networking and personal connections');
3592
+ // recommendations.push('May be used for freelance or consulting work');
3593
+ // }
3594
+
3595
+ // if (data.spam_risk_level === 'high') {
3596
+ // recommendations.push('Consider verifying before important communications');
3597
+ // }
3598
+
3599
+ // if (!data.is_likely_active) {
3600
+ // recommendations.push('Email may not be actively monitored');
3601
+ // }
3602
+
3603
+ // return recommendations;
3604
+ // }
3605
+
3606
+ // function generateVerificationSuggestions(data, emailContext) {
3607
+ // const suggestions = [];
3608
+
3609
+ // if (data.account_type === 'business' && !data.business_company_name) {
3610
+ // suggestions.push('Verify company name through LinkedIn or company website');
3611
+ // }
3612
+
3613
+ // if (!data.is_real_person && data.account_type === 'business') {
3614
+ // suggestions.push('Check if this is a role-based email that forwards to individuals');
3615
+ // }
3616
+
3617
+ // if (data.spam_risk_level === 'medium' || data.spam_risk_level === 'high') {
3618
+ // suggestions.push('Send verification email before important communications');
3619
+ // }
3620
+
3621
+ // if (data.domain_analysis.is_custom_domain) {
3622
+ // suggestions.push('Check company website for email format patterns');
3623
+ // }
3624
+
3625
+ // return suggestions;
3626
+ // }
3627
+
3628
+ // function getDefaultEmailAnalysis(name, email, emailContext = '', error = null) {
3629
+ // const domain = email.split('@')[1] || '';
3630
+ // const localPart = email.split('@')[0] || '';
3631
+ // const nameParts = name.toLowerCase().split(/\s+/);
3632
+ // const firstName = nameParts[0] || '';
3633
+ // const lastName = nameParts.slice(-1)[0] || '';
3634
+
3635
+ // const isPublicProvider = isPublicEmailProvider(domain);
3636
+ // const accountType = isPublicProvider ? 'personal' : 'business';
3637
+ // const isRealPerson = detectRealPerson(localPart, name, domain);
3638
+
3639
+ // return {
3640
+ // success: false,
3641
+ // account_type: accountType,
3642
+ // account_type_confidence: 70,
3643
+
3644
+ // personal_account_provider: isPublicProvider ? identifyPersonalProvider(domain) : undefined,
3645
+ // personal_account_type: 'unknown',
3646
+ // personal_account_age_indicator: 'unknown',
3647
+
3648
+ // business_company_name: !isPublicProvider ? inferCompanyFromDomain(domain) : undefined,
3649
+ // business_company_domain: !isPublicProvider ? domain : undefined,
3650
+ // business_account_category: !isPublicProvider ? (isRealPerson ? 'personal_employee' : 'generic_role') : undefined,
3651
+ // business_account_role: undefined,
3652
+ // business_department: undefined,
3653
+
3654
+ // is_real_person: isRealPerson,
3655
+ // person_name_in_email: checkNameInEmail(localPart, firstName, lastName),
3656
+ // person_title_inferred: undefined,
3657
+
3658
+ // email_pattern: analyzeEmailPattern(localPart, domain),
3659
+
3660
+ // context_supports_business: undefined,
3661
+ // context_supports_personal: undefined,
3662
+ // context_company_mentions: [],
3663
+
3664
+ // is_high_quality_contact: isRealPerson && !isPublicProvider,
3665
+ // is_likely_active: true,
3666
+ // spam_risk_level: assessSpamRisk(localPart, domain, accountType),
3667
+
3668
+ // suggested_use_case: isRealPerson && !isPublicProvider ? 'sales_outreach' : 'networking',
3669
+
3670
+ // analysis_timestamp: new Date().toISOString(),
3671
+ // analysis_notes: ['Default analysis due to API failure'],
3672
+
3673
+ // // Enhanced fields
3674
+ // domain_analysis: {
3675
+ // domain: domain,
3676
+ // is_public_provider: isPublicProvider,
3677
+ // is_custom_domain: isCustomDomain(domain),
3678
+ // is_free_email: isFreeEmailDomain(domain),
3679
+ // is_education: isEducationDomain(domain),
3680
+ // is_government: isGovernmentDomain(domain),
3681
+ // tld: domain.split('.').pop() || '',
3682
+ // },
3683
+
3684
+ // name_email_correlation: calculateNameEmailCorrelation(localPart, firstName, lastName),
3685
+ // professional_score: calculateProfessionalScore({
3686
+ // account_type: accountType,
3687
+ // is_real_person: isRealPerson,
3688
+ // is_likely_active: true,
3689
+ // spam_risk_level: assessSpamRisk(localPart, domain, accountType),
3690
+ // name_email_correlation: calculateNameEmailCorrelation(localPart, firstName, lastName),
3691
+ // business_account_category: !isPublicProvider ? (isRealPerson ? 'personal_employee' : 'generic_role') : undefined,
3692
+ // }),
3693
+
3694
+ // recommendations: generateRecommendations({
3695
+ // account_type: accountType,
3696
+ // is_real_person: isRealPerson,
3697
+ // business_account_category: !isPublicProvider ? (isRealPerson ? 'personal_employee' : 'generic_role') : undefined,
3698
+ // spam_risk_level: assessSpamRisk(localPart, domain, accountType),
3699
+ // is_likely_active: true,
3700
+ // }),
3701
+
3702
+ // verification_suggestions: generateVerificationSuggestions(
3703
+ // {
3704
+ // account_type: accountType,
3705
+ // business_company_name: !isPublicProvider ? inferCompanyFromDomain(domain) : undefined,
3706
+ // is_real_person: isRealPerson,
3707
+ // spam_risk_level: assessSpamRisk(localPart, domain, accountType),
3708
+ // domain_analysis: { is_custom_domain: isCustomDomain(domain) },
3709
+ // },
3710
+ // emailContext,
3711
+ // ),
3712
+
3713
+ // error: error || 'API call failed',
3714
+ // };
3715
+ // }
3716
+
3717
+ // const analysis_ret = await submit_chat_gpt_prompt({
3718
+ // uid,
3719
+ // prompt: `Analyze this email account: "${email}" for person: "${name}"
3720
+
3721
+ // EMAIL CONTEXT (if provided):
3722
+ // "${email_context.substring(0, 400)}${email_context.length > 400 ? '...' : ''}"
3723
+
3724
+ // ANALYSIS TASKS:
3725
+ // 1. Determine if this is a PERSONAL or BUSINESS email account
3726
+ // 2. For BUSINESS accounts:
3727
+ // - Identify the company/organization
3728
+ // - Determine if this email belongs to a REAL PERSON at the company
3729
+ // - Or if it's a generic/role-based account
3730
+ // 3. For PERSONAL accounts:
3731
+ // - Identify which personal email provider is used
3732
+ // - Determine if it's likely a primary or secondary personal account
3733
+
3734
+ // ANALYSIS CRITERIA:
3735
+ // BUSINESS EMAIL INDICATORS:
3736
+ // - Domain matches a known company (not public email providers)
3737
+ // - Email format matches company naming conventions
3738
+ // - Email is mentioned in professional context
3739
+ // - Contains company-specific signature or details
3740
+
3741
+ // PERSONAL EMAIL INDICATORS:
3742
+ // - Domain is from public email providers (gmail.com, outlook.com, yahoo.com, etc.)
3743
+ // - Email format is personal/creative
3744
+ // - No company affiliation in context
3745
+ // - Used for personal communications
3746
+
3747
+ // PERSON VS GENERIC BUSINESS ACCOUNT:
3748
+ // - PERSON: Contains personal name elements (john.doe@company.com)
3749
+ // - GENERIC: info@, support@, sales@, contact@, hello@, noreply@, etc.
3750
+ // - DEPARTMENT: hr@, finance@, marketing@, it@, etc.
3751
+
3752
+ // COMPANY DETECTION:
3753
+ // - Extract company from email domain when possible
3754
+ // - Use name patterns to identify likely companies
3755
+ // - Consider email context for company references
3756
+
3757
+ // PROVIDE DETAILED ANALYSIS WITH CONFIDENCE LEVELS.`,
3758
+ // model: 'gpt-5-nano',
3759
+ // response_format: z.object({
3760
+ // // Primary Classification
3761
+ // account_type: z.enum(['personal', 'business', 'ambiguous']),
3762
+ // account_type_confidence: z.number().min(0).max(100),
3763
+
3764
+ // // Personal Account Details
3765
+ // personal_account_provider: z.string().optional().nullable().describe('Email provider for personal accounts'),
3766
+ // personal_account_type: z.enum(['primary', 'secondary', 'disposable', 'unknown']).optional().nullable(),
3767
+ // personal_account_age_indicator: z.enum(['new', 'established', 'old', 'unknown']).optional().nullable(),
3768
+
3769
+ // // Business Account Details
3770
+ // business_company_name: z.string().optional().nullable().describe('Company name if business account'),
3771
+ // business_company_domain: z.string().optional().nullable().describe('Company domain'),
3772
+ // business_account_category: z.enum(['personal_employee', 'generic_role', 'department', 'catch_all', 'unknown']).optional().nullable(),
3773
+ // business_account_role: z.string().optional().nullable().describe('Role suggested by email address'),
3774
+ // business_department: z.string().optional().nullable().describe('Department if applicable'),
3775
+
3776
+ // // Person Analysis
3777
+ // is_real_person: z.boolean().describe('Whether email belongs to a real person'),
3778
+ // person_name_in_email: z.boolean().describe("Whether person's name appears in email address"),
3779
+ // person_title_inferred: z.string().optional().nullable().describe('Inferred job title from email pattern'),
3780
+
3781
+ // // Email Pattern Analysis
3782
+ // email_pattern: z.enum([
3783
+ // 'first.last@company.com',
3784
+ // 'first.last@domain.com',
3785
+ // 'firstlast@company.com',
3786
+ // 'flast@company.com',
3787
+ // 'first@company.com',
3788
+ // 'f.last@company.com',
3789
+ // 'initial.last@company.com',
3790
+ // 'role@company.com',
3791
+ // 'department@company.com',
3792
+ // 'info@company.com',
3793
+ // 'generic@company.com',
3794
+ // 'personal@provider.com',
3795
+ // 'custom@personal.com',
3796
+ // 'unknown',
3797
+ // ]),
3798
+
3799
+ // // Context Analysis
3800
+ // context_supports_business: z.boolean().optional().nullable().describe('Email context suggests business use'),
3801
+ // context_supports_personal: z.boolean().optional().nullable().describe('Email context suggests personal use'),
3802
+ // context_company_mentions: z.array(z.string()).optional().nullable().describe('Companies mentioned in context'),
3803
+
3804
+ // // Risk & Quality Assessment
3805
+ // is_high_quality_contact: z.boolean().describe('Good contact for professional outreach'),
3806
+ // is_likely_active: z.boolean().describe('Email likely actively monitored'),
3807
+ // spam_risk_level: z.enum(['low', 'medium', 'high', 'unknown']),
3808
+
3809
+ // // Recommendations
3810
+ // suggested_use_case: z.enum(['sales_outreach', 'recruitment', 'customer_support', 'partnership', 'networking', 'personal_contact', 'avoid']),
3811
+
3812
+ // // Metadata
3813
+ // analysis_timestamp: z.string().describe('When analysis was performed'),
3814
+ // analysis_notes: z.array(z.string()).optional().nullable().describe('Key observations from analysis'),
3815
+ // }),
3816
+ // metadata: {
3817
+ // func: 'analyze_email_account_type',
3818
+ // person_name: name,
3819
+ // person_email: email,
3820
+ // has_email_context: !!email_context,
3821
+ // email_length: email_context?.length || 0,
3822
+ // },
3823
+ // account_profile_info,
3824
+ // tools: [{ type: 'web_search_preview' }],
3825
+ // });
3826
+
3827
+ // try {
3828
+ // if (analysis_ret.code > -1) {
3829
+ // const data = typeof analysis_ret.data === 'string' ? JSON.parse(analysis_ret.data) : analysis_ret.data;
3830
+
3831
+ // // Enhance with additional analysis
3832
+ // const enhancedData = enhanceEmailAnalysis(data, name, email, email_context);
3833
+
3834
+ // return {
3835
+ // success: true,
3836
+ // ...enhancedData,
3837
+ // };
3838
+ // } else {
3839
+ // console.error('Email analysis API call failed:', analysis_ret);
3840
+ // return getDefaultEmailAnalysis(name, email, email_context);
3841
+ // }
3842
+ // } catch (error) {
3843
+ // console.error('Error in analyze_email_account_type:', error);
3844
+ // return getDefaultEmailAnalysis(name, email, email_context, error.message);
3845
+ // }
3846
+ // };
3847
+
3848
+ // export const detect_email_type = async function (uid, name, email, account_profile_info, email_body = '', email_subject = '') {
3849
+ // // ========== HELPER FUNCTIONS ==========
3850
+
3851
+ // async function hashString(str) {
3852
+ // const encoder = new TextEncoder();
3853
+ // const data = encoder.encode(str);
3854
+ // const hashBuffer = await crypto.subtle.digest('SHA-256', data);
3855
+ // const hashArray = Array.from(new Uint8Array(hashBuffer));
3856
+ // return hashArray
3857
+ // .map((b) => b.toString(16).padStart(2, '0'))
3858
+ // .join('')
3859
+ // .substring(0, 16);
3860
+ // }
3861
+
3862
+ // function enhanceEmailDetection(data, name, email, emailBody, emailSubject) {
3863
+ // // Run additional local analysis
3864
+ // const localAnalysis = analyzeEmailLocally(emailBody, emailSubject, email, name);
3865
+
3866
+ // // Combine AI analysis with local analysis
3867
+ // const combinedData = {
3868
+ // ...data,
3869
+ // // Override with local analysis if confidence is high
3870
+ // spam_confidence: Math.max(data.spam_confidence, localAnalysis.spamScore),
3871
+ // phishing_risk: localAnalysis.phishingScore > 70 ? 'high' : data.phishing_risk,
3872
+
3873
+ // // Add local analysis results
3874
+ // local_analysis: localAnalysis,
3875
+
3876
+ // // Enhance sender analysis
3877
+ // sender_analysis: analyzeSender(email, name, emailBody),
3878
+
3879
+ // // Content statistics
3880
+ // content_stats: {
3881
+ // word_count: (emailBody.match(/\S+/g) || []).length,
3882
+ // sentence_count: (emailBody.match(/[.!?]+/g) || []).length,
3883
+ // link_count: (emailBody.match(/https?:\/\/[^\s]+/g) || []).length,
3884
+ // uppercase_ratio: calculateUppercaseRatio(emailBody),
3885
+ // exclamation_count: (emailBody.match(/!/g) || []).length,
3886
+ // dollar_sign_count: (emailBody.match(/\$/g) || []).length,
3887
+ // phone_patterns: (emailBody.match(/\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g) || []).length,
3888
+ // },
3889
+
3890
+ // // Behavioral patterns
3891
+ // behavioral_patterns: detectBehavioralPatterns(emailBody, emailSubject),
3892
+
3893
+ // // Domain reputation
3894
+ // domain_reputation: assessDomainReputation(email),
3895
+
3896
+ // // Add comprehensive risk assessment
3897
+ // comprehensive_risk_score: calculateComprehensiveRisk(data, localAnalysis),
3898
+
3899
+ // // Filter rules that matched
3900
+ // matched_filters: detectMatchedFilters(emailBody, emailSubject, email, name),
3901
+
3902
+ // // Timeline analysis
3903
+ // temporal_analysis: {
3904
+ // is_time_sensitive: detectTimeSensitivity(emailBody),
3905
+ // has_expiry: detectExpiryDate(emailBody),
3906
+ // is_follow_up: detectFollowUpPattern(emailBody, emailSubject),
3907
+ // },
3908
+
3909
+ // // Relationship context
3910
+ // relationship_context: analyzeRelationshipContext(emailBody, emailSubject, name),
3911
+
3912
+ // // Update timestamp
3913
+ // analysis_timestamp: new Date().toISOString(),
3914
+ // content_length: emailBody.length,
3915
+ // };
3916
+
3917
+ // // Calculate final classification confidence
3918
+ // combinedData.final_confidence = calculateFinalConfidence(combinedData);
3919
+
3920
+ // // Generate detailed explanation
3921
+ // combinedData.explanation = generateExplanation(combinedData);
3922
+
3923
+ // // Add compliance flags
3924
+ // combinedData.compliance_flags = checkCompliance(emailBody, emailSubject);
3925
+
3926
+ // return combinedData;
3927
+ // }
3928
+
3929
+ // function analyzeEmailLocally(body, subject, email, name) {
3930
+ // const text = (subject + ' ' + body).toLowerCase();
3931
+ // let spamScore = 0;
3932
+ // let phishingScore = 0;
3933
+ // let promotionalScore = 0;
3934
+ // let transactionalScore = 0;
3935
+
3936
+ // // SPAM indicators
3937
+ // const spamKeywords = [
3938
+ // 'congratulations',
3939
+ // 'winner',
3940
+ // 'prize',
3941
+ // 'lottery',
3942
+ // 'free',
3943
+ // 'guaranteed',
3944
+ // 'risk-free',
3945
+ // 'act now',
3946
+ // 'limited time',
3947
+ // 'urgent',
3948
+ // 'important',
3949
+ // 'attention',
3950
+ // 'alert',
3951
+ // 'click here',
3952
+ // 'buy now',
3953
+ // 'order now',
3954
+ // 'discount',
3955
+ // 'save big',
3956
+ // 'cheap',
3957
+ // 'viagra',
3958
+ // 'cialis',
3959
+ // 'pharmacy',
3960
+ // 'prescription',
3961
+ // 'enlarge',
3962
+ // 'weight loss',
3963
+ // 'nigerian',
3964
+ // 'prince',
3965
+ // 'inheritance',
3966
+ // 'unclaimed',
3967
+ // 'bank account',
3968
+ // 'password',
3969
+ // 'account suspended',
3970
+ // 'verify',
3971
+ // 'security alert',
3972
+ // 'dear friend',
3973
+ // 'dear customer',
3974
+ // 'dear account holder',
3975
+ // ];
3976
+
3977
+ // spamKeywords.forEach((keyword) => {
3978
+ // if (text.includes(keyword)) spamScore += 2;
3979
+ // });
3980
+
3981
+ // // Phishing indicators
3982
+ // const phishingPatterns = [/login\s*(?:here|now)/i, /verify\s*(?:your|my)\s*account/i, /password\s*(?:reset|expired|change)/i, /suspended\s*account/i, /unauthorized\s*activity/i, /security\s*breach/i, /update\s*(?:your|my)\s*information/i, /confirm\s*(?:your|my)\s*identity/i];
3983
+
3984
+ // phishingPatterns.forEach((pattern) => {
3985
+ // if (pattern.test(text)) phishingScore += 15;
3986
+ // });
3987
+
3988
+ // // Promotional indicators
3989
+ // const promotionalKeywords = ['newsletter', 'subscribe', 'unsubscribe', 'marketing', 'promotion', 'sale', 'offer', 'deal', 'coupon', 'voucher', 'discount code', 'new product', 'announcement', 'launch', 'event', 'webinar', 'limited offer', 'exclusive', 'special offer', 'members only'];
3990
+
3991
+ // promotionalKeywords.forEach((keyword) => {
3992
+ // if (text.includes(keyword)) promotionalScore += 3;
3993
+ // });
3994
+
3995
+ // // Transactional indicators
3996
+ // const transactionalKeywords = ['order', 'invoice', 'receipt', 'payment', 'booking', 'reservation', 'confirmation', 'shipping', 'delivery', 'tracking', 'shipment', 'appointment', 'meeting', 'reminder', 'bill', 'statement', 'account', 'statement', 'balance', 'transaction'];
3997
+
3998
+ // transactionalKeywords.forEach((keyword) => {
3999
+ // if (text.includes(keyword)) transactionalScore += 3;
4000
+ // });
4001
+
4002
+ // // Link analysis
4003
+ // const links = body.match(/https?:\/\/[^\s]+/g) || [];
4004
+ // const suspiciousDomains = ['bit.ly', 'tinyurl', 'shorte.st', 'adf.ly', 'goo.gl'];
4005
+
4006
+ // links.forEach((link) => {
4007
+ // if (suspiciousDomains.some((domain) => link.includes(domain))) {
4008
+ // spamScore += 10;
4009
+ // phishingScore += 10;
4010
+ // }
4011
+ // });
4012
+
4013
+ // // Grammar/spelling analysis (simple)
4014
+ // const misspellings = body.match(/\b(?:recieve|seperate|definately|occured|tomm?orrow)\b/gi) || [];
4015
+ // spamScore += misspellings.length * 2;
4016
+
4017
+ // // Urgency analysis
4018
+ // const urgencyWords = ['urgent', 'immediately', 'asap', 'right now', 'today only'];
4019
+ // let urgencyCount = 0;
4020
+ // urgencyWords.forEach((word) => {
4021
+ // if (text.includes(word)) urgencyCount++;
4022
+ // });
4023
+ // spamScore += urgencyCount * 5;
4024
+
4025
+ // // Personalization check
4026
+ // const hasName = name && body.toLowerCase().includes(name.toLowerCase().split(' ')[0]);
4027
+ // const personalPronouns = ['you', 'your', 'yours'];
4028
+ // let personalCount = 0;
4029
+ // personalPronouns.forEach((pronoun) => {
4030
+ // const regex = new RegExp(`\\b${pronoun}\\b`, 'gi');
4031
+ // personalCount += (body.match(regex) || []).length;
4032
+ // });
4033
+
4034
+ // const personalizationScore = hasName ? 30 : Math.min(personalCount * 2, 20);
4035
+
4036
+ // return {
4037
+ // spamScore: Math.min(spamScore, 100),
4038
+ // phishingScore: Math.min(phishingScore, 100),
4039
+ // promotionalScore: Math.min(promotionalScore, 100),
4040
+ // transactionalScore: Math.min(transactionalScore, 100),
4041
+ // personalizationScore,
4042
+ // linkCount: links.length,
4043
+ // hasUnsubscribe: text.includes('unsubscribe') || text.includes('opt-out'),
4044
+ // hasPhone: /\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/.test(body),
4045
+ // hasAddress: /\b\d+\s+[\w\s]+(?:street|st|avenue|ave|road|rd|boulevard|blvd|way)\b/i.test(body),
4046
+ // urgencyCount,
4047
+ // misspellingCount: misspellings.length,
4048
+ // };
4049
+ // }
4050
+
4051
+ // function analyzeSender(email, name, body) {
4052
+ // const domain = email.split('@')[1] || '';
4053
+ // const localPart = email.split('@')[0] || '';
4054
+
4055
+ // return {
4056
+ // email: email,
4057
+ // domain: domain,
4058
+ // local_part: localPart,
4059
+ // is_public_domain: isPublicEmailDomain(domain),
4060
+ // is_generic_sender: isGenericSender(localPart, name),
4061
+ // domain_age_indicator: assessDomainAge(domain),
4062
+ // sender_consistency: checkSenderConsistency(name, email, body),
4063
+ // };
4064
+ // }
4065
+
4066
+ // function isPublicEmailDomain(domain) {
4067
+ // const publicDomains = ['gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com', 'aol.com', 'icloud.com', 'protonmail.com', 'zoho.com', 'yandex.com'];
4068
+ // return publicDomains.includes(domain.toLowerCase());
4069
+ // }
4070
+
4071
+ // function isGenericSender(localPart, name) {
4072
+ // const genericSenders = ['info', 'support', 'sales', 'contact', 'hello', 'noreply', 'admin', 'newsletter', 'marketing', 'team', 'notifications'];
4073
+
4074
+ // const localLower = localPart.toLowerCase();
4075
+ // const nameLower = name.toLowerCase();
4076
+
4077
+ // return genericSenders.some((sender) => localLower.includes(sender) || nameLower.includes(sender));
4078
+ // }
4079
+
4080
+ // function assessDomainAge(domain) {
4081
+ // // This is a simplified version - in production, you'd use a domain age API
4082
+ // const newDomains = ['xyz', 'online', 'site', 'top', 'club', 'shop'];
4083
+ // const tld = domain.split('.').pop() || '';
4084
+
4085
+ // if (newDomains.includes(tld)) return 'likely_new';
4086
+ // if (['com', 'org', 'net', 'edu', 'gov'].includes(tld)) return 'likely_established';
4087
+ // return 'unknown';
4088
+ // }
4089
+
4090
+ // function checkSenderConsistency(name, email, body) {
4091
+ // const emailName = email.split('@')[0].toLowerCase();
4092
+ // const bodyName = name.toLowerCase();
4093
+
4094
+ // // Check if name appears in body
4095
+ // const nameInBody = body.toLowerCase().includes(bodyName.split(' ')[0]);
4096
+
4097
+ // // Check email-name consistency patterns
4098
+ // const nameParts = bodyName.split(' ');
4099
+ // const firstName = nameParts[0] || '';
4100
+ // const lastName = nameParts.slice(-1)[0] || '';
4101
+
4102
+ // const patterns = [`${firstName}.${lastName}`, `${firstName}${lastName}`, `${firstName.charAt(0)}${lastName}`, `${firstName}`];
4103
+
4104
+ // const consistent = patterns.some((pattern) => emailName.includes(pattern.toLowerCase()));
4105
+
4106
+ // return {
4107
+ // name_in_body: nameInBody,
4108
+ // email_name_consistent: consistent,
4109
+ // consistency_score: (nameInBody ? 40 : 0) + (consistent ? 60 : 0),
4110
+ // };
4111
+ // }
4112
+
4113
+ // function calculateUppercaseRatio(text) {
4114
+ // const letters = text.replace(/[^a-zA-Z]/g, '');
4115
+ // if (letters.length === 0) return 0;
4116
+
4117
+ // const uppercase = letters.replace(/[^A-Z]/g, '');
4118
+ // return (uppercase.length / letters.length) * 100;
4119
+ // }
4120
+
4121
+ // function detectBehavioralPatterns(body, subject) {
4122
+ // const text = (subject + ' ' + body).toLowerCase();
4123
+ // const patterns = [];
4124
+
4125
+ // if (/(?:click|tap)\s+(?:here|this|link|button)/i.test(text)) {
4126
+ // patterns.push('call_to_action_link');
4127
+ // }
4128
+
4129
+ // if (/limited\s+time|offer\s+expires|only\s+\d+\s+left/i.test(text)) {
4130
+ // patterns.push('scarcity_tactic');
4131
+ // }
4132
+
4133
+ // if (/\$\d+|\d+\s*%|\d+\s*off|discount|save|sale/i.test(text)) {
4134
+ // patterns.push('monetary_offer');
4135
+ // }
4136
+
4137
+ // if (/urgent|important|alert|attention|warning/i.test(text)) {
4138
+ // patterns.push('urgency_tactic');
4139
+ // }
4140
+
4141
+ // if (/(?:please|kindly)\s+(?:help|assist|reply)/i.test(text)) {
4142
+ // patterns.push('polite_request');
4143
+ // }
4144
+
4145
+ // if (/unsubscribe|opt.?out|preference|manage subscription/i.test(text)) {
4146
+ // patterns.push('subscription_management');
4147
+ // }
4148
+
4149
+ // return patterns;
4150
+ // }
4151
+
4152
+ // function assessDomainReputation(email) {
4153
+ // const domain = email.split('@')[1] || '';
4154
+
4155
+ // // Known spam domains (simplified list)
4156
+ // const spamDomains = ['spam4.me', 'trashmail.com', 'mailinator.com', 'guerrillamail.com', 'tempmail.com', 'yopmail.com', 'dispostable.com'];
4157
+
4158
+ // if (spamDomains.includes(domain.toLowerCase())) {
4159
+ // return 'known_spam_domain';
4160
+ // }
4161
+
4162
+ // // Professional domains
4163
+ // const professionalTLDs = ['com', 'org', 'net', 'edu', 'gov', 'io', 'ai', 'tech'];
4164
+ // const tld = domain.split('.').pop() || '';
4165
+
4166
+ // if (professionalTLDs.includes(tld.toLowerCase())) {
4167
+ // return 'professional_domain';
4168
+ // }
4169
+
4170
+ // // New/suspicious TLDs
4171
+ // const suspiciousTLDs = ['xyz', 'top', 'win', 'bid', 'download', 'stream'];
4172
+ // if (suspiciousTLDs.includes(tld.toLowerCase())) {
4173
+ // return 'suspicious_tld';
4174
+ // }
4175
+
4176
+ // return 'neutral';
4177
+ // }
4178
+
4179
+ // function calculateComprehensiveRisk(aiData, localAnalysis) {
4180
+ // let risk = 0;
4181
+
4182
+ // // Base on AI classification
4183
+ // switch (aiData.email_type) {
4184
+ // case 'spam':
4185
+ // risk += 80;
4186
+ // break;
4187
+ // case 'promotional':
4188
+ // risk += 30;
4189
+ // break;
4190
+ // case 'transactional':
4191
+ // risk += 10;
4192
+ // break;
4193
+ // case 'personal':
4194
+ // risk += 5;
4195
+ // break;
4196
+ // case 'business':
4197
+ // risk += 15;
4198
+ // break;
4199
+ // }
4200
+
4201
+ // // Add local analysis scores
4202
+ // risk += localAnalysis.spamScore * 0.2;
4203
+ // risk += localAnalysis.phishingScore * 0.3;
4204
+
4205
+ // // Adjust for phishing risk
4206
+ // switch (aiData.phishing_risk) {
4207
+ // case 'critical':
4208
+ // risk += 40;
4209
+ // break;
4210
+ // case 'high':
4211
+ // risk += 30;
4212
+ // break;
4213
+ // case 'medium':
4214
+ // risk += 15;
4215
+ // break;
4216
+ // case 'low':
4217
+ // risk += 5;
4218
+ // break;
4219
+ // }
4220
+
4221
+ // // Adjust for unsolicited
4222
+ // if (aiData.is_unsolicited) risk += 20;
4223
+
4224
+ // // Adjust for urgency
4225
+ // if (aiData.is_urgent) risk += 10;
4226
+
4227
+ // return Math.min(risk, 100);
4228
+ // }
4229
+
4230
+ // function detectMatchedFilters(body, subject, email, name) {
4231
+ // const filters = [];
4232
+ // const text = (subject + ' ' + body).toLowerCase();
4233
+
4234
+ // // Spam filters
4235
+ // if (/(?:viagra|cialis|penis|enlarge)/i.test(text)) filters.push('adult_content_filter');
4236
+ // if (/(?:lottery|winner|prize|jackpot)/i.test(text)) filters.push('lottery_scam_filter');
4237
+ // if (/(?:nigerian|prince|inheritance|unclaimed)/i.test(text)) filters.push('inheritance_scam_filter');
4238
+ // if (/password\s+reset|verify\s+account/i.test(text)) filters.push('account_verification_filter');
4239
+
4240
+ // // Promotional filters
4241
+ // if (/newsletter|subscribe|unsubscribe/i.test(text)) filters.push('newsletter_filter');
4242
+ // if (/sale|discount|offer|coupon/i.test(text)) filters.push('promotional_offer_filter');
4243
+ // if (/webinar|event|conference/i.test(text)) filters.push('event_filter');
4244
+
4245
+ // // Transactional filters
4246
+ // if (/order|invoice|receipt|payment/i.test(text)) filters.push('transaction_filter');
4247
+ // if (/shipping|delivery|tracking/i.test(text)) filters.push('shipping_filter');
4248
+ // if (/appointment|meeting|reminder/i.test(text)) filters.push('calendar_filter');
4249
+
4250
+ // return filters;
4251
+ // }
4252
+
4253
+ // function detectTimeSensitivity(body) {
4254
+ // const text = body.toLowerCase();
4255
+ // const patterns = [/today|tomorrow|this\s+week|immediately|asap/i, /deadline|due\s+by|expires|limited\s+time/i, /urgent|important|attention|alert/i];
4256
+
4257
+ // return patterns.some((pattern) => pattern.test(text));
4258
+ // }
4259
+
4260
+ // function detectExpiryDate(body) {
4261
+ // const datePatterns = [/\b\d{1,2}\/\d{1,2}\/\d{2,4}\b/g, /\b\d{1,2}\s+(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\s+\d{2,4}\b/gi, /\bexpires?\s+(?:on|by)?\s*[:]?\s*\d{1,2}\/\d{1,2}\/\d{2,4}\b/gi];
4262
+
4263
+ // return datePatterns.some((pattern) => pattern.test(body.toLowerCase()));
4264
+ // }
4265
+
4266
+ // function detectFollowUpPattern(body, subject) {
4267
+ // const text = (subject + ' ' + body).toLowerCase();
4268
+ // return /follow.?up|following.?up|checking.?in|touch.?base|re:.?re:/i.test(text);
4269
+ // }
4270
+
4271
+ // function analyzeRelationshipContext(body, subject, name) {
4272
+ // const text = (subject + ' ' + body).toLowerCase();
4273
+ // const nameParts = name.toLowerCase().split(' ');
4274
+ // const firstName = nameParts[0] || '';
4275
+
4276
+ // const indicators = {
4277
+ // uses_name: firstName && text.includes(firstName),
4278
+ // uses_personal_pronouns: /\b(?:i|me|my|mine|you|your|yours)\b/gi.test(text),
4279
+ // has_greeting: /^(?:hi|hello|hey|dear|greetings)\b/im.test(body),
4280
+ // has_signature: /(?:best|regards|sincerely|thanks|thank you)\s*[,]?\s*\n/im.test(body),
4281
+ // has_questions: /\?/.test(text) && /(?:can|could|would|will|do|are|is)\s+you/i.test(text),
4282
+ // };
4283
+
4284
+ // const relationshipScore = Object.values(indicators).filter(Boolean).length * 20;
4285
+
4286
+ // return {
4287
+ // ...indicators,
4288
+ // relationship_score: Math.min(relationshipScore, 100),
4289
+ // likely_known_sender: relationshipScore >= 40,
4290
+ // };
4291
+ // }
4292
+
4293
+ // function calculateFinalConfidence(data) {
4294
+ // let confidence = data.email_type_confidence;
4295
+
4296
+ // // Adjust based on local analysis
4297
+ // if (data.local_analysis.spamScore > 70 && data.email_type !== 'spam') {
4298
+ // confidence -= 20;
4299
+ // }
4300
+
4301
+ // // Adjust based on phishing risk
4302
+ // if (data.phishing_risk === 'critical' || data.phishing_risk === 'high') {
4303
+ // confidence += 15;
4304
+ // }
4305
+
4306
+ // // Adjust based on personalization
4307
+ // if (data.is_personalized) {
4308
+ // confidence += 10;
4309
+ // }
4310
+
4311
+ // // Adjust based on content stats
4312
+ // if (data.content_stats.link_count > 5) {
4313
+ // confidence += 5;
4314
+ // }
4315
+
4316
+ // return Math.max(0, Math.min(100, confidence));
4317
+ // }
4318
+
4319
+ // function generateExplanation(data) {
4320
+ // const explanations = [];
4321
+
4322
+ // if (data.email_type === 'spam') {
4323
+ // explanations.push('Classified as spam due to:');
4324
+ // if (data.spam_confidence > 70) explanations.push(`- High spam confidence (${data.spam_confidence}%)`);
4325
+ // if (data.phishing_risk !== 'none') explanations.push(`- ${data.phishing_risk} phishing risk`);
4326
+ // if (data.local_analysis.spamScore > 60) explanations.push('- Contains spam indicators');
4327
+ // }
4328
+
4329
+ // if (data.email_type === 'promotional') {
4330
+ // explanations.push('Classified as promotional due to:');
4331
+ // if (data.is_commercial) explanations.push('- Commercial intent detected');
4332
+ // if (data.local_analysis.hasUnsubscribe) explanations.push('- Contains unsubscribe option');
4333
+ // if (data.local_analysis.promotionalScore > 30) explanations.push('- Promotional content detected');
4334
+ // }
4335
+
4336
+ // if (data.key_indicators && data.key_indicators.length > 0) {
4337
+ // explanations.push('Key indicators:');
4338
+ // data.key_indicators.forEach((indicator) => {
4339
+ // explanations.push(`- ${indicator}`);
4340
+ // });
4341
+ // }
4342
+
4343
+ // return explanations.join('\n');
4344
+ // }
4345
+
4346
+ // function checkCompliance(body, subject) {
4347
+ // const text = (subject + ' ' + body).toLowerCase();
4348
+ // const flags = [];
4349
+
4350
+ // // CAN-SPAM Act compliance (US)
4351
+ // if (text.includes('unsubscribe') || text.includes('opt-out')) {
4352
+ // flags.push('has_unsubscribe_option');
4353
+ // }
4354
+
4355
+ // if (/\b\d{10}\b/.test(body.replace(/\D/g, ''))) {
4356
+ // flags.push('contains_phone_number');
4357
+ // }
4358
+
4359
+ // if (/address\s*[:]?\s*\d+\s+[\w\s]+/i.test(body)) {
4360
+ // flags.push('contains_physical_address');
4361
+ // }
4362
+
4363
+ // // GDPR indicators (EU)
4364
+ // if (/privacy\s+policy|gdpr|data\s+protection/i.test(text)) {
4365
+ // flags.push('gdpr_mentions');
4366
+ // }
4367
+
4368
+ // if (/consent|opt.?in|permission/i.test(text)) {
4369
+ // flags.push('consent_mentions');
4370
+ // }
4371
+
4372
+ // return flags;
4373
+ // }
4374
+
4375
+ // function getDefaultEmailDetection(name, email, emailBody, emailSubject, error = null) {
4376
+ // const localAnalysis = analyzeEmailLocally(emailBody, emailSubject, email, name);
4377
+
4378
+ // // Determine type based on local analysis
4379
+ // let emailType = 'ambiguous';
4380
+ // if (localAnalysis.spamScore > 70) emailType = 'spam';
4381
+ // else if (localAnalysis.promotionalScore > localAnalysis.transactionalScore && localAnalysis.promotionalScore > 30) emailType = 'promotional';
4382
+ // else if (localAnalysis.transactionalScore > 40) emailType = 'transactional';
4383
+
4384
+ // const spamConfidence = localAnalysis.spamScore;
4385
+ // const phishingRisk = localAnalysis.phishingScore > 50 ? 'medium' : 'low';
4386
+
4387
+ // return {
4388
+ // success: false,
4389
+ // email_type: emailType,
4390
+ // email_type_confidence: Math.max(50, spamConfidence),
4391
+ // email_subtype: 'personal_message',
4392
+
4393
+ // spam_confidence: spamConfidence,
4394
+ // phishing_risk: phishingRisk,
4395
+ // malware_risk: 'none',
4396
+
4397
+ // is_unsolicited: true,
4398
+ // is_commercial: localAnalysis.promotionalScore > 30,
4399
+ // is_urgent: localAnalysis.urgencyCount > 0,
4400
+ // is_personalized: localAnalysis.personalizationScore > 20,
4401
+
4402
+ // sender_legitimacy: 'unknown',
4403
+ // sender_intent: 'unknown',
4404
+
4405
+ // contains_links: localAnalysis.linkCount > 0,
4406
+ // contains_attachments: false,
4407
+ // contains_unsubscribe: localAnalysis.hasUnsubscribe,
4408
+ // contains_phone_number: localAnalysis.hasPhone,
4409
+ // contains_address: localAnalysis.hasAddress,
4410
+
4411
+ // language_quality: localAnalysis.misspellingCount > 3 ? 'poor' : 'average',
4412
+ // urgency_level: localAnalysis.urgencyCount > 2 ? 'high' : 'low',
4413
+ // personalization_score: localAnalysis.personalizationScore,
4414
+
4415
+ // suggested_action: emailType === 'spam' ? 'mark_as_spam' : 'keep_in_inbox',
4416
+ // auto_filter_suggestion: emailType === 'spam' ? 'spam_filter' : 'no_filter',
4417
+ // inbox_priority: emailType === 'spam' ? 'ignore' : 'normal',
4418
+
4419
+ // key_indicators: ['Local analysis only - API failed'],
4420
+ // risk_factors: [],
4421
+ // legitimacy_signals: [],
4422
+
4423
+ // analysis_timestamp: new Date().toISOString(),
4424
+ // content_length: emailBody.length,
4425
+ // analysis_complexity: 'simple',
4426
+
4427
+ // // Enhanced fields
4428
+ // local_analysis: localAnalysis,
4429
+ // sender_analysis: analyzeSender(email, name, emailBody),
4430
+ // content_stats: {
4431
+ // word_count: (emailBody.match(/\S+/g) || []).length,
4432
+ // sentence_count: (emailBody.match(/[.!?]+/g) || []).length,
4433
+ // link_count: localAnalysis.linkCount,
4434
+ // uppercase_ratio: calculateUppercaseRatio(emailBody),
4435
+ // exclamation_count: (emailBody.match(/!/g) || []).length,
4436
+ // dollar_sign_count: (emailBody.match(/\$/g) || []).length,
4437
+ // phone_patterns: (emailBody.match(/\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g) || []).length,
4438
+ // },
4439
+
4440
+ // comprehensive_risk_score: calculateComprehensiveRisk({ email_type: emailType, phishing_risk: phishingRisk, is_unsolicited: true, is_urgent: localAnalysis.urgencyCount > 0 }, localAnalysis),
4441
+
4442
+ // final_confidence: Math.max(50, spamConfidence),
4443
+ // explanation: 'Default analysis due to API failure',
4444
+ // error: error || 'API call failed',
4445
+ // };
4446
+ // }
4447
+
4448
+ // const detection_ret = await submit_chat_gpt_prompt({
4449
+ // uid,
4450
+ // prompt: `Analyze this email and determine if it's SPAM, PROMOTIONAL, TRANSACTIONAL, or PERSONAL/BUSINESS communication.
4451
+
4452
+ // FROM: "${name}" <${email}>
4453
+ // SUBJECT: "${email_subject}"
4454
+ // BODY: "${email_body.substring(0, 800)}${email_body.length > 800 ? '...' : ''}"
4455
+
4456
+ // ANALYSIS CRITERIA:
4457
+
4458
+ // SPAM INDICATORS:
4459
+ // - Unsolicited commercial content
4460
+ // - Phishing attempts or suspicious links
4461
+ // - Poor grammar/spelling
4462
+ // - Urgent/panic-inducing language
4463
+ // - Requests for personal information
4464
+ // - Too good to be true offers
4465
+ // - Hidden/unclear sender identity
4466
+ // - Multiple recipient addresses visible
4467
+ // - Stock/"spammy" subject lines
4468
+
4469
+ // PROMOTIONAL INDICATORS:
4470
+ // - Marketing/sales content
4471
+ // - Product announcements
4472
+ // - Newsletter content
4473
+ // - Discount/coupon offers
4474
+ // - Event invitations (commercial)
4475
+ // - Company updates (marketing focused)
4476
+ // - Clear opt-out/unsubscribe option
4477
+ // - Professional branding/templates
4478
+ // - Call-to-action buttons
4479
+
4480
+ // TRANSACTIONAL INDICATORS:
4481
+ // - Order confirmations
4482
+ // - Shipping notifications
4483
+ // - Invoice/billing
4484
+ // - Account notifications
4485
+ // - Password resets
4486
+ // - Booking confirmations
4487
+ // - Appointment reminders
4488
+ // - Payment receipts
4489
+ // - Service updates
4490
+
4491
+ // PERSONAL/BUSINESS INDICATORS:
4492
+ // - Direct communication to you
4493
+ // - Known sender relationship
4494
+ // - Work/project related
4495
+ // - Personal conversations
4496
+ // - One-on-one correspondence
4497
+ // - Contains your name specifically
4498
+ // - Contextually relevant to you
4499
+
4500
+ // ADDITIONAL FACTORS TO CONSIDER:
4501
+ // - Sender reputation (company vs personal)
4502
+ // - Your relationship with sender
4503
+ // - Email formatting quality
4504
+ // - Personalization level
4505
+ // - Expected vs unexpected content
4506
+ // - Action requested (if any)
4507
+
4508
+ // PROVIDE DETAILED ANALYSIS WITH CONFIDENCE SCORES.`,
4509
+ // model: 'gpt-5-nano',
4510
+ // response_format: z.object({
4511
+ // // Primary Classification
4512
+ // email_type: z.enum(['spam', 'promotional', 'transactional', 'personal', 'business', 'ambiguous']),
4513
+ // email_type_confidence: z.number().min(0).max(100),
4514
+
4515
+ // // Sub-classification
4516
+ // email_subtype: z.enum([
4517
+ // // Spam types
4518
+ // 'phishing_attempt',
4519
+ // 'scam_offer',
4520
+ // 'malware_risk',
4521
+ // 'adult_content',
4522
+ // 'financial_scam',
4523
+ // 'lottery_scam',
4524
+ // 'inheritance_scam',
4525
+ // 'romance_scam',
4526
+ // 'tech_support_scam',
4527
+
4528
+ // // Promotional types
4529
+ // 'marketing_newsletter',
4530
+ // 'product_announcement',
4531
+ // 'discount_offer',
4532
+ // 'event_invitation',
4533
+ // 'company_update',
4534
+ // 'blog_newsletter',
4535
+ // 'educational_content',
4536
+ // 'lead_magnet',
4537
+
4538
+ // // Transactional types
4539
+ // 'order_confirmation',
4540
+ // 'shipping_notification',
4541
+ // 'invoice_billing',
4542
+ // 'payment_receipt',
4543
+ // 'account_verification',
4544
+ // 'password_reset',
4545
+ // 'appointment_reminder',
4546
+ // 'service_notification',
4547
+
4548
+ // // Personal/Business types
4549
+ // 'personal_message',
4550
+ // 'work_collaboration',
4551
+ // 'client_communication',
4552
+ // 'team_announcement',
4553
+ // 'meeting_invitation',
4554
+ // 'project_update',
4555
+ // 'direct_inquiry',
4556
+ // 'networking_request',
4557
+ // ]),
4558
+
4559
+ // // Risk Assessment
4560
+ // spam_confidence: z.number().min(0).max(100).describe('Confidence this is spam'),
4561
+ // phishing_risk: z.enum(['none', 'low', 'medium', 'high', 'critical']),
4562
+ // malware_risk: z.enum(['none', 'low', 'medium', 'high']),
4563
+
4564
+ // // Content Analysis
4565
+ // is_unsolicited: z.boolean().describe('Email was not requested/expected'),
4566
+ // is_commercial: z.boolean().describe('Contains commercial intent'),
4567
+ // is_urgent: z.boolean().describe('Uses urgent/time-sensitive language'),
4568
+ // is_personalized: z.boolean().describe('Content is personalized to recipient'),
4569
+
4570
+ // // Sender Analysis
4571
+ // sender_legitimacy: z.enum(['verified', 'likely_legitimate', 'suspicious', 'likely_fake', 'unknown']),
4572
+ // sender_intent: z.enum(['inform', 'sell', 'scam', 'build_relationship', 'request_action', 'unknown']),
4573
+
4574
+ // // Content Characteristics
4575
+ // contains_links: z.boolean(),
4576
+ // contains_attachments: z.boolean(),
4577
+ // contains_unsubscribe: z.boolean(),
4578
+ // contains_phone_number: z.boolean(),
4579
+ // contains_address: z.boolean(),
4580
+
4581
+ // // Language Analysis
4582
+ // language_quality: z.enum(['excellent', 'good', 'average', 'poor', 'spammy']),
4583
+ // urgency_level: z.enum(['none', 'low', 'medium', 'high', 'extreme']),
4584
+ // personalization_score: z.number().min(0).max(100).describe('How personalized the content is'),
4585
+
4586
+ // // Action Recommendations
4587
+ // suggested_action: z.enum(['delete_immediately', 'mark_as_spam', 'move_to_promotions', 'respond_politely', 'follow_up', 'archive', 'keep_in_inbox', 'add_to_contacts', 'report_phishing']),
4588
+
4589
+ // // Filter Recommendations
4590
+ // auto_filter_suggestion: z.enum(['spam_filter', 'promotions_filter', 'social_filter', 'updates_filter', 'primary_inbox', 'no_filter']),
4591
+
4592
+ // // Priority
4593
+ // inbox_priority: z.enum(['critical', 'high', 'normal', 'low', 'ignore']),
4594
+
4595
+ // // Detailed Analysis
4596
+ // key_indicators: z.array(z.string()).describe('Key factors influencing classification'),
4597
+ // risk_factors: z.array(z.string()).describe('Specific risks identified'),
4598
+ // legitimacy_signals: z.array(z.string()).describe('Signals of legitimate communication'),
4599
+
4600
+ // // Metadata
4601
+ // analysis_timestamp: z.string(),
4602
+ // content_length: z.number().describe('Length of email body analyzed'),
4603
+ // analysis_complexity: z.enum(['simple', 'moderate', 'complex', 'ambiguous']),
4604
+ // }),
4605
+ // metadata: {
4606
+ // func: 'detect_email_type',
4607
+ // sender_name: name,
4608
+ // sender_email: email,
4609
+ // subject_length: email_subject?.length || 0,
4610
+ // body_length: email_body?.length || 0,
4611
+ // body_preview_hash: await hashString(email_body.substring(0, 200)),
4612
+ // },
4613
+ // account_profile_info,
4614
+ // tools: [{ type: 'web_search_preview' }],
4615
+ // });
4616
+
4617
+ // try {
4618
+ // if (detection_ret.code > -1) {
4619
+ // const data = typeof detection_ret.data === 'string' ? JSON.parse(detection_ret.data) : detection_ret.data;
4620
+
4621
+ // // Enhance with additional analysis
4622
+ // const enhancedData = enhanceEmailDetection(data, name, email, email_body, email_subject);
4623
+
4624
+ // return {
4625
+ // success: true,
4626
+ // ...enhancedData,
4627
+ // };
4628
+ // } else {
4629
+ // console.error('Email detection API call failed:', detection_ret);
4630
+ // return getDefaultEmailDetection(name, email, email_body, email_subject);
4631
+ // }
4632
+ // } catch (error) {
4633
+ // console.error('Error in detect_email_type:', error);
4634
+ // return getDefaultEmailDetection(name, email, email_body, email_subject, error.message);
4635
+ // }
4636
+ // };
4637
+
4638
+
4639
+
4640
+ // export const get_business_info = async function (uid, name, email, account_profile_info) {
4641
+ // // Extract lists from your JSON categories array
4642
+ // const categories = [
4643
+ // {
4644
+ // id: 'ind_technology',
4645
+ // name: 'Technology',
4646
+ // sub: ['Software Development', 'AI & Machine Learning', 'Cybersecurity', 'Cloud Computing', 'IT Services', 'SaaS & Platforms', 'Hardware & Electronics'],
4647
+ // },
4648
+ // {
4649
+ // id: 'ind_marketing',
4650
+ // name: 'Marketing & Advertising',
4651
+ // sub: ['Digital Marketing', 'PPC & SEO', 'Content Creation', 'Branding', 'Social Media Management', 'Email Marketing', 'Market Research'],
4652
+ // },
4653
+ // {
4654
+ // id: 'ind_sales',
4655
+ // name: 'Sales',
4656
+ // sub: ['B2B Sales', 'B2C Sales', 'Real Estate Sales', 'Account Management', 'Lead Generation', 'Inside Sales', 'Field Sales'],
4657
+ // },
4658
+ // {
4659
+ // id: 'ind_finance',
4660
+ // name: 'Finance & Accounting',
4661
+ // sub: ['Banking', 'Investment', 'Financial Planning', 'Accounting', 'Bookkeeping', 'Insurance', 'FinTech'],
4662
+ // },
4663
+ // {
4664
+ // id: 'ind_healthcare',
4665
+ // name: 'Healthcare',
4666
+ // sub: ['Medical Clinics', 'Hospitals', 'Pharma', 'Mental Health', 'Healthcare IT', 'Home Care', 'Medical Research'],
4667
+ // },
4668
+ // {
4669
+ // id: 'ind_realestate',
4670
+ // name: 'Real Estate',
4671
+ // sub: ['Residential Real Estate', 'Commercial Real Estate', 'Property Management', 'Investment & BRRRR', 'Construction', 'Architecture', 'Interior Design'],
4672
+ // },
4673
+ // {
4674
+ // id: 'ind_ecommerce',
4675
+ // name: 'E-commerce',
4676
+ // sub: ['Online Store', 'Dropshipping', 'Amazon FBA', 'Marketplace Selling', 'Retail', 'Inventory Management', 'Fulfillment & Logistics'],
4677
+ // },
4678
+ // {
4679
+ // id: 'ind_education',
4680
+ // name: 'Education',
4681
+ // sub: ['Schools', 'Universities', 'Private Tutoring', 'Online Courses', 'EdTech', 'Training & Development'],
4682
+ // },
4683
+ // {
4684
+ // id: 'ind_hospitality',
4685
+ // name: 'Hospitality & Travel',
4686
+ // sub: ['Hotels', 'Restaurants', 'Cafes & Bars', 'Travel Agencies', 'Tourism', 'Events & Catering', 'Transportation'],
4687
+ // },
4688
+ // {
4689
+ // id: 'ind_professional',
4690
+ // name: 'Professional Services',
4691
+ // sub: ['Legal', 'Consulting', 'HR & Recruiting', 'Accounting Firms', 'Business Services', 'Management Consulting'],
4692
+ // },
4693
+ // {
4694
+ // id: 'ind_manufacturing',
4695
+ // name: 'Manufacturing',
4696
+ // sub: ['Automotive', 'Industrial', 'Textile', 'Electronics', 'Food Production', 'Machinery', 'Chemicals'],
4697
+ // },
4698
+ // {
4699
+ // id: 'ind_nonprofit',
4700
+ // name: 'Nonprofit & Government',
4701
+ // sub: ['NGOs', 'Municipality', 'Government Services', 'Public Health', 'Community Organizations', 'Education Programs'],
4702
+ // },
4703
+ // {
4704
+ // id: 'ind_media',
4705
+ // name: 'Media & Entertainment',
4706
+ // sub: ['Film & Video', 'Music', 'Publishing', 'Gaming', 'News & Journalism', 'Influencers', 'Production Studios'],
4707
+ // },
4708
+ // {
4709
+ // id: 'ind_logistics',
4710
+ // name: 'Logistics & Transportation',
4711
+ // sub: ['Shipping', 'Trucking', 'Last-Mile Delivery', 'Warehousing', 'Freight Forwarding', 'Route Optimization'],
4712
+ // },
4713
+ // {
4714
+ // id: 'ind_energy',
4715
+ // name: 'Energy & Utilities',
4716
+ // sub: ['Solar', 'Oil & Gas', 'Electricity Providers', 'Water Utilities', 'Environmental Services', 'Renewable Energy'],
4717
+ // },
4718
+ // {
4719
+ // id: 'ind_construction',
4720
+ // name: 'Construction & Trades',
4721
+ // sub: ['General Contracting', 'Roofing', 'Plumbing', 'HVAC', 'Electrical', 'Renovation', 'Engineering'],
4722
+ // },
4723
+ // {
4724
+ // id: 'ind_food',
4725
+ // name: 'Food & Beverage',
4726
+ // sub: ['Restaurants', 'Catering', 'Food Manufacturing', 'Bakeries', 'Bars & Nightlife', 'Food Delivery'],
4727
+ // },
4728
+ // {
4729
+ // id: 'ind_retail',
4730
+ // name: 'Retail',
4731
+ // sub: ['Physical Stores', 'Boutiques', 'Supermarkets', 'Consumer Goods', 'Fashion Retail', 'Home Goods'],
4732
+ // },
4733
+ // ];
4734
+ // const categoryNames = categories.map((c) => c.name);
4735
+ // const allSubCategories = categories.flatMap((c) => c.sub);
4736
+
4737
+ // const business_info_ret = await submit_chat_gpt_prompt({
4738
+ // uid,
4739
+ // prompt: `Research the company: "${name}" (${email}).
4740
+ // 1. get the company name.
4741
+ // 2. get the domain name from the email.
4742
+ // 2. Provide a professional one-sentence biography of the company.
4743
+ // 3. Categorize them using the provided industry lists.
4744
+ // 4. Identify their primary country as a 2-letter ISO code (e.g., 'US').`,
4745
+ // model: 'gpt-5-nano',
4746
+ // response_format: z.object({
4747
+ // business_name: z.string().describe('the company name'),
4748
+ // business_domain: z.string().describe('the email domain name'),
4749
+ // business_bio: z.string().describe('A concise, professional one-sentence summary of what the business does'),
4750
+ // business_size: z.enum(['unknown', 'small', 'medium', 'large', 'enterprise']),
4751
+ // business_category: z.enum(categoryNames),
4752
+ // business_sub_category: z.enum(allSubCategories),
4753
+ // business_country: z.string().length(2).describe("2-letter ISO country code (e.g., 'US')"),
4754
+ // }),
4755
+ // metadata: { func: 'get_business_info' },
4756
+ // account_profile_info,
4757
+ // tools: [{ type: 'web_search_preview' }],
4758
+ // });
4759
+
4760
+ // try {
4761
+ // if (business_info_ret.code > -1) {
4762
+ // const data = typeof business_info_ret.data === 'string' ? JSON.parse(business_info_ret.data) : business_info_ret.data;
4763
+
4764
+ // // Standardize country to uppercase
4765
+ // if (data.business_country) data.business_country = data.business_country.toUpperCase();
4766
+
4767
+ // // Logic to attach the ID for your database
4768
+ // const matched = categories.find((c) => c.name === data.business_category);
4769
+ // data.business_category_id = matched ? matched.id : null;
4770
+
4771
+ // return data;
4772
+ // }
4773
+ // } catch (error) {
4774
+ // console.error('Error in get_business_info:', error);
4775
+ // }
4776
+ // };