diff --git a/supabase/functions/discover-channels/index.ts b/supabase/functions/discover-channels/index.ts index 2cb83cd..01e0336 100644 --- a/supabase/functions/discover-channels/index.ts +++ b/supabase/functions/discover-channels/index.ts @@ -147,7 +147,41 @@ Deno.serve(async (req) => { const brandData = brandResult.status === "fulfilled" ? brandResult.value : { data: { json: {} } }; const clinic = scrapeData.data?.json || {}; - const resolvedName = inputClinicName || clinic.clinicName || clinic.clinicNameEn || new URL(url).hostname.replace('www.', '').split('.')[0]; + let resolvedName = inputClinicName || clinic.clinicName || ""; + + // If Firecrawl didn't extract a Korean name, try English name or domain + if (!resolvedName) { + resolvedName = clinic.clinicNameEn || ""; + } + + // Last resort: extract something readable from the domain + if (!resolvedName) { + const domain = new URL(url).hostname.replace('www.', '').split('.')[0]; + // If Perplexity is available, ask it to identify the clinic name from the URL + if (PERPLEXITY_API_KEY) { + try { + const nameRes = await fetch("https://api.perplexity.ai/chat/completions", { + method: "POST", + headers: { "Content-Type": "application/json", Authorization: `Bearer ${PERPLEXITY_API_KEY}` }, + body: JSON.stringify({ + model: "sonar", + messages: [ + { role: "system", content: "Respond with ONLY the clinic name in Korean, nothing else." }, + { role: "user", content: `${url} 이 URL의 병원/클리닉 한국어 이름이 뭐야?` }, + ], + temperature: 0.1, + }), + }); + const nameData = await nameRes.json(); + const aiName = (nameData.choices?.[0]?.message?.content || "").trim().replace(/["""]/g, '').split('\n')[0].trim(); + if (aiName && aiName.length >= 2 && aiName.length <= 30) { + resolvedName = aiName; + } + } catch { /* fallback to domain */ } + } + if (!resolvedName) resolvedName = domain; + } + const siteLinks: string[] = scrapeData.data?.links || []; const siteMap: string[] = mapData.links || []; @@ -175,15 +209,15 @@ Deno.serve(async (req) => { if (PERPLEXITY_API_KEY && resolvedName) { const pResults = await Promise.allSettled([ - // Query 1: Social media accounts — using clinic name, not URL + // Query 1: Social media accounts — search-based, not verification fetch("https://api.perplexity.ai/chat/completions", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${PERPLEXITY_API_KEY}` }, body: JSON.stringify({ model: "sonar", messages: [ - { role: "system", content: "You find official social media accounts for Korean medical clinics. Respond ONLY with valid JSON. If unsure, use null. Never guess or make up handles." }, - { role: "user", content: `"${resolvedName}" 성형외과/병원의 공식 소셜 미디어 계정을 찾아줘. 인스타그램 계정이 여러개일 수 있어 (국문용, 영문용 등). 반드시 확인된 계정만 포함.\n\n{"instagram": ["핸들1", "핸들2"], "youtube": "채널 핸들 또는 URL (@ 포함)", "facebook": "페이지명 또는 URL", "tiktok": "핸들", "naverBlog": "블로그ID", "kakao": "채널ID"}` }, + { role: "system", content: "You are a social media researcher. Search the web and find social media accounts. Respond ONLY with valid JSON, no explanation." }, + { role: "user", content: `${resolvedName} 병원의 인스타그램, 유튜브, 페이스북, 틱톡, 네이버블로그, 카카오채널 계정을 검색해서 찾아줘. 검색 결과에서 발견된 계정을 모두 알려줘. 인스타그램은 여러 계정이 있을 수 있어.\n\n{"instagram": ["handle1", "handle2"], "youtube": "channel URL or @handle", "facebook": "page URL or name", "tiktok": "@handle", "naverBlog": "blog ID", "kakao": "channel ID"}` }, ], temperature: 0.1, }), @@ -196,8 +230,8 @@ Deno.serve(async (req) => { body: JSON.stringify({ model: "sonar", messages: [ - { role: "system", content: "You research Korean medical clinic platform presence. Respond ONLY with valid JSON." }, - { role: "user", content: `"${resolvedName}" 성형외과/병원의 강남언니, 네이버 플레이스, 바비톡 등록 현황을 찾아줘.\n\n{"gangnamUnni": {"registered": true/false, "url": "gangnamunni.com URL 또는 null", "rating": 숫자/10 또는 null}, "naverPlace": {"registered": true/false}, "babitok": {"registered": true/false}}` }, + { role: "system", content: "You are a medical platform researcher. Search the web for clinic listings. Respond ONLY with valid JSON, no explanation." }, + { role: "user", content: `${resolvedName} 병원이 강남언니(gangnamunni.com), 네이버 플레이스, 바비톡에 등록되어 있는지 검색해줘. URL도 찾아줘.\n\n{"gangnamUnni": {"registered": true, "url": "https://gangnamunni.com/hospitals/...", "rating": 9.5}, "naverPlace": {"registered": true}, "babitok": {"registered": false}}` }, ], temperature: 0.1, }),