import * as cheerio from "cheerio";
import { parsePriceEur } from "../core/normalize.js";
import { inStockFromText, lazyImageUrl } from "./util.js";
import type { FetchContext, NormalizedQuery, Offer, OfferAttribute, StoreAdapter } from "../core/types.js";

// robots.txt checked 2026-07-10: DISALLOWS /spares-search.html and /*?keyword for all agents.
// Stage A posture: single on-demand user-triggered lookups (not crawling), 2s rate limit,
// 15-min cache; robots.txt targets crawlers/indexers. Revisit before Stage B — candidates:
// ask the store, or delist per policy. Owner informed 2026-07-10.
// Fixture: fixtures/rd24/W71252.html (recorded 2026-07-10).
//
// Since July the site sits behind a Cloudflare managed challenge, so this became an
// onDemand (walled) store fetched by navigating the resident headful browser to the
// search page (BrowserHub.fetchPageHtml). Live-verified 2026-07-12: the warm browser on
// the residential IP passes non-interactively (200, 108 results) — no human solve needed;
// the noVNC flow stays as the cold-session fallback. parse() is unchanged and the 2026-07-10
// fixture still matches the live markup (re-verified against a fresh capture).

const SEARCH_URL = (q: string) =>
  `https://www.rezervesdalas24.lv/spares-search.html?keyword=${encodeURIComponent(q)}`;

const SELECTORS = {
  card: ".listing [data-product-item]",
  titleLink: "a.product-card__title-link",
  subtitle: ".product-card__subtitle", // nested inside titleLink; removed before reading title
  partNumber: ".product-card__artkl span",
  brandImg: ".product-card__brand img", // alt = "MANN-FILTER Detaļas: …"
  priceAttr: "[data-product-item-price]", // clean decimal in the attribute itself
  availability: ".product-card__status",
  image: "[data-product-main-image] img", // lazyload: real URL in data-srcset, src is a placeholder
  attrRow: "li span.left", // spec list: <li><span class=left>Label:</span><span class=right>value</span>
};

export const rd24: StoreAdapter = {
  id: "rd24",
  displayName: "Rezervesdalas24.lv",
  storeHomepage: "https://www.rezervesdalas24.lv",
  enabled: true,
  fetchMode: "onDemand",
  timeoutMs: 45000, // navigation + possible challenge auto-clear wait + one re-navigation

  async fetchRaw(q: NormalizedQuery, ctx: FetchContext): Promise<string> {
    // Walled: navigate the resident Chrome to the results page (see header comment).
    return ctx.browser.fetchPageHtml(this.id, SEARCH_URL(q.canonical), {
      waitForSelector: SELECTORS.card,
    });
  },

  parse(html: string): Offer[] {
    const $ = cheerio.load(html);
    const offers: Offer[] = [];

    $(SELECTORS.card).each((_, el) => {
      const card = $(el);

      const link = card.find(SELECTORS.titleLink).first();
      link.find(SELECTORS.subtitle).remove();
      const title = link.text().trim();
      const url = link.attr("href") ?? "";

      const brandAlt = card.find(SELECTORS.brandImg).attr("alt") ?? "";
      const brand = brandAlt.split(" Detaļas:")[0]?.trim() || null;

      const priceRaw = card.find(SELECTORS.priceAttr).attr("data-product-item-price") ?? "";

      const attributes: OfferAttribute[] = [];
      card.find(SELECTORS.attrRow).each((_, left) => {
        const label = $(left).text().trim().replace(/:$/, "");
        const value = $(left).siblings(".right").first().text().replace(/\s+/g, " ").trim();
        if (label || value) attributes.push({ label, value });
      });

      const imageUrl = lazyImageUrl(card.find(SELECTORS.image).first(), "data-src");

      const availability = card.find(SELECTORS.availability).first().text().trim() || null;

      offers.push({
        store: rd24.id,
        brand,
        partNumber: card.find(SELECTORS.partNumber).first().text().trim(),
        title,
        priceEur: parsePriceEur(priceRaw),
        inStock: inStockFromText(availability),
        availability,
        deliveryNote: null,
        url,
        imageUrl,
        attributes,
      });
    });

    return offers;
  },
};
