import { q as query } from '../../../chunks/db_Du3AmLCY.mjs';
export { renderers } from '../../../renderers.mjs';

const MODEL_FAMILY_PATTERNS = {
  nike: [
    { patterns: [/air\s*max/i], slug: "nike/air-max", activity: "lifestyle", tags: ["retro"] },
    { patterns: [/air\s*force\s*1/i, /\baf1\b/i], slug: "nike/air-force-1", activity: "lifestyle" },
    { patterns: [/\bdunk\b/i], slug: "nike/dunk", activity: "lifestyle", tags: ["retro"] },
    { patterns: [/air\s*jordan/i, /\baj\d/i, /\bjordan\s*\d/i], slug: "nike/air-jordan", activity: "basketball/lifestyle" },
    { patterns: [/\bblazer\b/i], slug: "nike/blazer", activity: "lifestyle", tags: ["retro"] },
    { patterns: [/\bcortez\b/i], slug: "nike/cortez", activity: "lifestyle", tags: ["retro"] },
    { patterns: [/\bpegasus\b/i, /\bvomero\b/i], slug: "nike/pegasus", activity: "running" }
  ],
  adidas: [
    { patterns: [/\bsuperstar\b/i], slug: "adidas/superstar", activity: "lifestyle", tags: ["retro"] },
    { patterns: [/\bstan\s*smith\b/i], slug: "adidas/stan-smith", activity: "lifestyle", tags: ["retro"] },
    { patterns: [/\bforum\b/i], slug: "adidas/forum", activity: "lifestyle" },
    { patterns: [/\b(gazelle|samba|spezial)\b/i], slug: "adidas/samba", activity: "lifestyle", tags: ["retro"] },
    { patterns: [/ultra\s*boost/i], slug: "adidas/ultraboost", activity: "running" },
    { patterns: [/\bnmd\b/i], slug: "adidas/nmd", activity: "lifestyle" },
    { patterns: [/\byeezy\b/i], slug: "adidas/yeezy", activity: "lifestyle" },
    { patterns: [/\bcampus\b/i], slug: "adidas/campus", activity: "lifestyle", tags: ["retro"] }
  ],
  "new balance": [
    { patterns: [/\b550\b/], slug: "new-balance/550", activity: "lifestyle", tags: ["retro"] },
    { patterns: [/\b574\b/], slug: "new-balance/574", activity: "lifestyle" },
    { patterns: [/\b99[0-3]\b/], slug: "new-balance/990", activity: "lifestyle" },
    { patterns: [/\b2002r?\b/i], slug: "new-balance/2002r", activity: "lifestyle" },
    { patterns: [/\b1906r?\b/i], slug: "new-balance/1906r", activity: "lifestyle" }
  ],
  puma: [
    { patterns: [/\bsuede\b/i], slug: "puma/suede", activity: "lifestyle", tags: ["retro"] },
    { patterns: [/\brs-?x\b/i], slug: "puma/rs-x", activity: "lifestyle" }
  ],
  converse: [
    { patterns: [/chuck\s*(taylor|70|all\s*star)/i, /\ball\s*star\b/i], slug: "converse/chuck-taylor", activity: "lifestyle", tags: ["retro"] },
    { patterns: [/\bone\s*star\b/i], slug: "converse/one-star", activity: "lifestyle" }
  ],
  vans: [
    { patterns: [/old\s*skool/i], slug: "vans/old-skool", activity: "skateboarding" },
    { patterns: [/sk8[\s-]*hi/i], slug: "vans/sk8-hi", activity: "skateboarding" },
    { patterns: [/\b(authentic|era)\b/i], slug: "vans/authentic", activity: "skateboarding" }
  ],
  asics: [
    { patterns: [/gel[\s-]*lyte/i], slug: "asics/gel-lyte", activity: "lifestyle", tags: ["retro"] },
    { patterns: [/gel[\s-]*kayano/i], slug: "asics/gel-kayano", activity: "running" },
    { patterns: [/gel[\s-]*(1130|nyc)/i], slug: "asics/gel-1130", activity: "lifestyle" }
  ],
  reebok: [
    { patterns: [/classic\s*leather/i], slug: "reebok/classic-leather", activity: "lifestyle", tags: ["retro"] },
    { patterns: [/club\s*c/i], slug: "reebok/club-c", activity: "lifestyle", tags: ["retro"] }
  ],
  "on running": [
    { patterns: [/cloud\s*5/i], slug: "on-running/cloud-5", activity: "running" },
    { patterns: [/cloudmonster/i], slug: "on-running/cloudmonster", activity: "running" },
    { patterns: [/cloudnova/i], slug: "on-running/cloudnova", activity: "lifestyle" }
  ],
  salomon: [
    { patterns: [/\bxt[\s-]*6\b/i], slug: "salomon/xt-6", activity: "walking" },
    { patterns: [/speedcross/i], slug: "salomon/speedcross", activity: "running/trail" },
    { patterns: [/acs\s*pro/i], slug: "salomon/acs-pro", activity: "walking" }
  ]
};
const GENDER_PATTERNS = [
  { patterns: [/\bwmns\b/i, /\bwomen'?s?\b/i, /\bdames\b/i, /\bw's\b/i], gender: "women" },
  { patterns: [/\bmen'?s?\b/i, /\bheren\b/i], gender: "men" },
  { patterns: [/\b(gs|grade\s*school)\b/i, /\bkids?\b/i, /\bjunior\b/i, /\bkinderen\b/i], gender: "kids" },
  { patterns: [/\btoddler\b/i, /\btd\b/i, /\bpeuter\b/i], gender: "kids/toddler" },
  { patterns: [/\b(ps|preschool)\b/i], gender: "kids" },
  { patterns: [/\binfant\b/i, /\bbaby\b/i], gender: "kids/infant" }
];
const ACTIVITY_PATTERNS = [
  { patterns: [/\brunning\b/i, /\bhardloop/i, /\brunner\b/i, /\brun\b/i], slug: "running" },
  { patterns: [/\bbasketbal/i, /\bhoops?\b/i], slug: "basketball" },
  { patterns: [/\bskate\b/i, /\bsb\b/i], slug: "skateboarding" },
  { patterns: [/\btraining\b/i, /\bgym\b/i, /\bcross[\s-]?fit/i], slug: "training" },
  { patterns: [/\bfootball\b/i, /\bvoetbal/i, /\bsoccer\b/i], slug: "football" },
  { patterns: [/\btennis\b/i, /\bpadel\b/i], slug: "tennis" },
  { patterns: [/\bhiking?\b/i, /\btrail\b/i, /\boutdoor\b/i, /\bwandel/i], slug: "walking" }
];

function normalize(name) {
  return name.toLowerCase().replace(/[''`]/g, "").replace(/[-_\/\\]/g, " ").replace(/\s+/g, " ").replace(/\bwmns\b/g, "women").replace(/\bgs\b/g, "grade school").replace(/\btd\b/g, "toddler").replace(/\bps\b/g, "preschool").trim();
}
function detectBrand(product) {
  if (product.brand) return product.brand.toLowerCase();
  const name = product.name.toLowerCase();
  const brands = [
    "nike",
    "adidas",
    "new balance",
    "puma",
    "converse",
    "vans",
    "asics",
    "reebok",
    "on running",
    "salomon",
    "jordan"
  ];
  for (const brand of brands) {
    if (name.includes(brand)) return brand === "jordan" ? "nike" : brand;
  }
  return null;
}
function detectGender(normalized, feedGender) {
  for (const { patterns, gender } of GENDER_PATTERNS) {
    for (const pattern of patterns) {
      if (pattern.test(normalized)) return gender;
    }
  }
  if (feedGender) {
    const g = feedGender.toLowerCase();
    if (["heren", "men", "male", "man"].some((k) => g.includes(k))) return "men";
    if (["dames", "women", "female", "vrouw"].some((k) => g.includes(k))) return "women";
    if (["unisex"].some((k) => g.includes(k))) return "unisex";
    if (["kids", "kinderen", "junior"].some((k) => g.includes(k))) return "kids";
  }
  return null;
}
function detectModelFamily(brand, normalized) {
  const brandPatterns = MODEL_FAMILY_PATTERNS[brand];
  if (!brandPatterns) return null;
  for (const family of brandPatterns) {
    for (const pattern of family.patterns) {
      if (pattern.test(normalized)) {
        return { slug: family.slug, activity: family.activity, tags: family.tags };
      }
    }
  }
  return null;
}
function detectActivity(normalized, feedCategory) {
  const text = `${normalized} ${feedCategory || ""}`.toLowerCase();
  for (const { patterns, slug } of ACTIVITY_PATTERNS) {
    for (const pattern of patterns) {
      if (pattern.test(text)) return slug;
    }
  }
  return null;
}
function categorizeProduct(product) {
  const normalized = normalize(product.name);
  const result = {
    productId: product.id,
    categories: [],
    tags: [],
    detectedGender: null,
    detectedBrand: null,
    detectedActivity: null
  };
  const brand = detectBrand(product);
  result.detectedBrand = brand;
  if (brand) {
    const brandSlugMap = {
      "nike": "nike",
      "adidas": "adidas",
      "new balance": "new-balance",
      "puma": "puma",
      "converse": "converse",
      "vans": "vans",
      "asics": "asics",
      "reebok": "reebok",
      "on running": "on-running",
      "salomon": "salomon"
    };
    const brandSlug = brandSlugMap[brand];
    if (brandSlug) {
      result.categories.push({ slug: brandSlug, dimension: "brand_family", isPrimary: true, confidence: 1 });
    }
  }
  const gender = detectGender(normalized, product.gender);
  result.detectedGender = gender;
  if (gender) {
    result.categories.push({ slug: gender, dimension: "gender", isPrimary: true, confidence: 1 });
  }
  if (brand) {
    const family = detectModelFamily(brand, normalized);
    if (family) {
      result.categories.push({ slug: family.slug, dimension: "brand_family", isPrimary: true, confidence: 1 });
      if (family.activity) {
        result.detectedActivity = family.activity;
        result.categories.push({ slug: family.activity, dimension: "activity", isPrimary: true, confidence: 0.9 });
      }
      if (family.tags) {
        result.tags.push(...family.tags);
      }
    }
  }
  if (!result.detectedActivity) {
    const activity = detectActivity(normalized, product.feed_category);
    if (activity) {
      result.detectedActivity = activity;
      result.categories.push({ slug: activity, dimension: "activity", isPrimary: true, confidence: 0.8 });
    } else {
      result.detectedActivity = "lifestyle";
      result.categories.push({ slug: "lifestyle", dimension: "activity", isPrimary: true, confidence: 0.5 });
    }
  }
  return result;
}
async function writeCategorizationResults(results) {
  let written = 0;
  for (const result of results) {
    const catMap = /* @__PURE__ */ new Map();
    for (const cat of result.categories) {
      const existing = catMap.get(cat.slug);
      if (!existing || cat.confidence > existing.confidence) {
        catMap.set(cat.slug, cat);
      }
    }
    for (const cat of catMap.values()) {
      try {
        await query(
          `INSERT INTO product_categories (product_id, category_id, is_primary, confidence, source)
           SELECT $1, c.id, $3, $4, 'rule'
           FROM categories c WHERE c.slug = $2
           ON CONFLICT (product_id, category_id) DO UPDATE
           SET confidence = GREATEST(product_categories.confidence, EXCLUDED.confidence),
               source = CASE WHEN product_categories.source = 'manual' THEN 'manual' ELSE EXCLUDED.source END`,
          [result.productId, cat.slug, cat.isPrimary, cat.confidence]
        );
        written++;
      } catch (e) {
      }
    }
    const uniqueTags = [...new Set(result.tags)];
    for (const tagSlug of uniqueTags) {
      try {
        await query(
          `INSERT INTO product_tags (product_id, tag_id, source)
           SELECT $1, t.id, 'rule'
           FROM tags t WHERE t.slug = $2
           ON CONFLICT (product_id, tag_id) DO NOTHING`,
          [result.productId, tagSlug]
        );
      } catch (e) {
      }
    }
    await query(
      `UPDATE products SET
        categorized_at = now(),
        categorization_version = categorization_version + 1,
        gender = COALESCE($2, gender),
        brand = COALESCE($3, brand)
       WHERE id = $1`,
      [result.productId, result.detectedGender, result.detectedBrand]
    );
  }
  return written;
}
async function autoCategorize(options = {}) {
  const whereClause = options.all ? "WHERE 1=1" : "WHERE categorized_at IS NULL OR categorization_version = 0";
  const { rows: products } = await query(
    `SELECT p.id, p.name, p.brand, p.gender, p.price, p.original_price
     FROM products p
     ${whereClause}
     AND NOT EXISTS (
       SELECT 1 FROM product_categories pc
       WHERE pc.product_id = p.id AND pc.source = 'manual'
     )
     ORDER BY p.created_at DESC`
  );
  const results = [];
  for (const product of products) {
    results.push(categorizeProduct(product));
  }
  const written = await writeCategorizationResults(results);
  return { processed: products.length, categorized: written };
}

const POST = async ({ request }) => {
  try {
    const body = await request.json().catch(() => ({}));
    const all = body.all === true;
    const result = await autoCategorize({ all });
    return new Response(JSON.stringify(result), {
      headers: { "Content-Type": "application/json" }
    });
  } catch (e) {
    return new Response(JSON.stringify({ error: e.message }), { status: 500 });
  }
};

const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  __proto__: null,
  POST
}, Symbol.toStringTag, { value: 'Module' }));

const page = () => _page;

export { page };
