import { ILeadSource, NormalizedLead, SearchParams, SourceCategory } from "./types";
import { z } from "zod";

export class WebsiteContactSource implements ILeadSource {
  id = "website-contact";
  name = "Website Contact Extractor";
  description = "Scrapes publicly visible contact information (emails, phones) directly from a business website.";
  category: SourceCategory = "extraction";

  inputSchema = z.object({
    domain: z.string().min(1, "Domain or URL is required"),
  });

  async run(params: SearchParams): Promise<NormalizedLead[]> {
    if (!params.domain) {
      throw new Error("Domain is required for website contact extraction.");
    }

    const targetUrl = params.domain.startsWith("http") ? params.domain : `https://${params.domain}`;
    
    try {
      // Note: In a real server-side Next.js environment, simple fetch might be blocked by CORS or bot detection.
      // This is a simplified version. A production version would use a scraping API like Apify or a headless browser.
      const response = await fetch(targetUrl, { signal: AbortSignal.timeout(10000) });
      const html = await response.text();

      // Simple regex for emails
      const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
      const emails = Array.from(new Set(html.match(emailRegex) || []));

      // Simple regex for phones (US/International)
      const phoneRegex = /(\+?\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}/g;
      const phones = Array.from(new Set(html.match(phoneRegex) || []));

      // Extract title as business name
      const titleMatch = html.match(/<title>(.*?)<\/title>/i);
      const businessName = titleMatch ? titleMatch[1].trim() : params.domain;

      if (emails.length === 0 && phones.length === 0) {
        return [];
      }

      const leads: NormalizedLead[] = emails.map(email => ({
        businessName,
        website: targetUrl,
        email: email,
        phone: phones[0], // Take first phone if available
        confidenceScore: 0.7,
        rawData: { source: "scraping", foundEmails: emails, foundPhones: phones }
      }));

      // If only phone found
      if (leads.length === 0 && phones.length > 0) {
        leads.push({
          businessName,
          website: targetUrl,
          phone: phones[0],
          confidenceScore: 0.6,
          rawData: { source: "scraping", foundPhones: phones }
        });
      }

      return leads;
    } catch (error) {
      console.error(`Scraping error for ${targetUrl}:`, error);
      return [];
    }
  }

  isAvailable(): boolean {
    return true; // Basic fetch usually available
  }
}
