import * as cheerio from "cheerio";
import { Property } from "../types/property";
import { PlaywrightBaseScraper } from "./playwrightBaseScraper";

/**
 * Scraper para Kyero (portal propiedades internacionales; protección CloudFlare).
 * Playwright ejecuta Chromium real para intentar pasar el desafío JS de CloudFlare.
 */
export class KyeroScraper extends PlaywrightBaseScraper {
  protected waitForSelector = '[class*="listing-card"], [class*="property-card"], [data-testid*="property"]';
  protected pageTimeoutMs = 45000;

  constructor() { super("https://www.kyero.com", "Kyero"); }

  async scrape(): Promise<Property[]> {
    const zones = await this.getActiveZones();
    const targets = zones.length > 0
      ? zones.map(z => `${this.baseUrl}/es/propiedades-baratas/esp-valencia/${z.slug}-valencia`)
      : [`${this.baseUrl}/es/propiedades-baratas/esp-valencia/lliria-valencia`];

    const properties: Property[] = [];
    const seenUrls = new Set<string>();

    for (const url of targets) {
      const html = await this.fetchHtmlPlaywright(url, this.waitForSelector);
      if (!html) continue;
      const $ = cheerio.load(html);

      $('[class*="listing-card"], [class*="property-card"], [data-testid*="property"], article[class*="property"]').each((_i, el) => {
        try {
          const title = this.sanitizeText(
            $(el).find('h2, h3, [class*="title"], [class*="heading"]').first().text() || "Propiedad Kyero"
          );
          const priceRaw = this.sanitizeText(
            $(el).find('[class*="price"], [class*="Price"]').first().text()
          );
          const price = this.parsePrice(priceRaw);
          const href =
            $(el).find('a[href*="/es/property"]').first().attr('href') ||
            $(el).find('a[href]').first().attr('href') || '';
          const absUrl = href.startsWith('http') ? href : `${this.baseUrl}${href}`;
          const location = this.sanitizeText(
            $(el).find('[class*="location"], [class*="address"], [class*="town"]').first().text()
          );
          const rooms = parseInt($(el).find('[class*="bed"], [class*="room"]').first().text()) || 0;
          const size_m2 = parseInt($(el).find('[class*="size"], [class*="area"]').first().text()) || 0;
          const image_url = $(el).find('img').first().attr('src') || '';

          if (price > 0 && !seenUrls.has(absUrl)) {
            seenUrls.add(absUrl);
            properties.push({
              title, price, location,
              municipality: this.detectMunicipality(location, zones),
              property_type: this.normalizeType(title),
              rooms, size_m2, url: absUrl,
              source: this.sourceName, image_url,
            });
          }
        } catch { /* skip */ }
      });
    }
    return this.validateResults(properties);
  }
}

