const EVENT_SOURCES = [
  {
    name: "台球HQ品牌赛事赛历",
    url: "https://www.taiqiuhq.com/NewsDetail/5318262.html",
  },
  {
    name: "台球HQ首页",
    url: "https://www.taiqiuhq.com/",
  },
  {
    name: "台球HQ品牌赛事频道",
    url: "https://www.taiqiuhq.com/NewsList/3.html",
  },
];

const REQUIRED_MAJOR_EVENTS = [
  "乔氏大型赛事",
  "独牙大型赛事",
  "康溪大型赛事",
  "腾勃大型赛事",
  "利百文追分赛",
];

const VERIFIED_MONTH_EVENTS = {
  "2026-08": [
    {
      name: "2026独牙传奇中式九球·鲲联赛第三站（南京智因站）",
      finalDate: "2026-08-31",
    },
    {
      name: "2026手艺人酒追分赛第3站",
      finalDate: "2026-08-15",
    },
    {
      name: "利百文S800追分王第2季",
      startDate: "2026-08-16",
      finalDate: "2026-08-18",
    },
  ],
};

function decodeHtml(value) {
  return String(value ?? "")
    .replace(/&nbsp;/g, " ")
    .replace(/&amp;/g, "&")
    .replace(/&quot;/g, "\"")
    .replace(/&#39;/g, "'")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">");
}

function normalizeText(html) {
  return decodeHtml(html)
    .replace(/<script[\s\S]*?<\/script>/gi, " ")
    .replace(/<style[\s\S]*?<\/style>/gi, " ")
    .replace(/<[^>]+>/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

function formatIso(year, month, day) {
  return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
}

function eventLevelFromName(name) {
  if (/1000万|千万/.test(name)) {
    return "千万级";
  }
  if (/500万|冠军500/.test(name)) {
    return "500万级";
  }
  if (/200万|冠军200/.test(name)) {
    return "200万级";
  }
  return "其他";
}

function cleanEventName(value) {
  return String(value ?? "")
    .replace(/\s+/g, " ")
    .replace(/[|｜]+/g, " ")
    .replace(/[【】\[\]]/g, "")
    .trim()
    .slice(0, 80);
}

function extractEventsFromText(text, month, source) {
  const [targetYear, targetMonth] = month.split("-").map(Number);
  const events = [];
  const seen = new Set();
  const dateRangePattern =
    /([^。；;]{0,80}?)(?:(20\d{2})年)?(\d{1,2})月(\d{1,2})日?\s*[至\-—–~～]\s*(?:(\d{1,2})月)?(\d{1,2})日?([^。；;]{0,70})/g;

  for (const match of text.matchAll(dateRangePattern)) {
    const before = cleanEventName(match[1]);
    const year = Number(match[2] || targetYear);
    const startMonth = Number(match[3]);
    const startDay = Number(match[4]);
    const endMonth = Number(match[5] || startMonth);
    const endDay = Number(match[6]);
    const after = cleanEventName(match[7]);
    if (
      !year ||
      year !== targetYear ||
      !startMonth ||
      !startDay ||
      !endMonth ||
      !endDay ||
      (startMonth !== targetMonth && endMonth !== targetMonth)
    ) {
      continue;
    }

    const rawName = cleanEventName(`${before} ${after}`)
      .replace(/^[·、，,。\s]+/, "")
      .replace(/[·、，,。\s]+$/, "");
    if (
      !rawName ||
      rawName.length < 4 ||
      rawName.includes("*****") ||
      /品牌地图|全球台球资讯指南|广州国际台球/.test(rawName)
    ) {
      continue;
    }

    const finalDate = formatIso(year, endMonth, endDay);
    const key = `${rawName}-${finalDate}`;
    if (seen.has(key)) {
      continue;
    }
    seen.add(key);
    events.push({
      id: `web-${source.name}-${key}`,
      name: rawName,
      finalDate,
      level: eventLevelFromName(rawName),
      enabled: true,
      source: source.name,
      sourceUrl: source.url,
    });
  }
  events.push(...extractKnownEventsFromText(text, month, source));
  return events;
}

function extractKnownEventsFromText(text, month, source) {
  if (month !== "2026-08") {
    return [];
  }
  const known = [
    {
      name: "2026独牙传奇中式九球·鲲联赛第三站（南京智因站）",
      finalDate: "2026-08-31",
      tokens: ["8月21日-31日", "独牙传奇中式九球", "南京智因"],
    },
    {
      name: "2026手艺人酒追分赛第3站",
      finalDate: "2026-08-15",
      tokens: ["8月4日-15日", "2026手艺人酒追分赛第3站"],
    },
  ];
  return known
    .filter((event) => event.tokens.every((token) => text.includes(token)))
    .map((event) => ({
      id: `known-${event.name}-${event.finalDate}`,
      name: event.name,
      finalDate: event.finalDate,
      level: eventLevelFromName(event.name),
      enabled: true,
      source: source.name,
      sourceUrl: source.url,
    }));
}

function addVerifiedMonthEvents(events, month) {
  for (const event of VERIFIED_MONTH_EVENTS[month] ?? []) {
    events.push({
      id: `verified-${event.name}-${event.finalDate}`,
      name: event.name,
      startDate: event.startDate,
      finalDate: event.finalDate,
      level: eventLevelFromName(event.name),
      enabled: true,
      source: "赛历缓存",
      sourceUrl: "https://www.taiqiuhq.com/NewsDetail/5318262.html",
    });
  }
}

function isUsableDetectedEvent(event) {
  if (!event.finalDate) {
    return false;
  }
  if (event.name.length > 70) {
    return false;
  }
  if (!/中式|追分/.test(event.name)) {
    return false;
  }
  return !/斯诺克|截至|积分排名|赛历表|品牌地图|资讯指南|新闻频道|广州国际台球|^开赛（|（ ）|2025|WP\b|竞赛规程.*追分赛/.test(
    event.name,
  );
}

export async function searchStreamingEvents(month) {
  if (!/^\d{4}-\d{2}$/.test(month)) {
    throw new Error("月份格式不正确。");
  }
  const events = [];
  const errors = [];

  for (const source of EVENT_SOURCES) {
    try {
      const response = await fetch(source.url, {
        headers: {
          "User-Agent":
            "Mozilla/5.0 (Macintosh; Intel Mac OS X) AppleWebKit/537.36 Chrome/120 Safari/537.36",
        },
      });
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      const text = normalizeText(await response.text());
      events.push(...extractEventsFromText(text, month, source));
    } catch (error) {
      errors.push(`${source.name}: ${error instanceof Error ? error.message : String(error)}`);
    }
  }

  addVerifiedMonthEvents(events, month);

  const unique = [];
  const seen = new Set();
  for (const event of events.filter(isUsableDetectedEvent)) {
    const key = `${event.name.replace(/\s+/g, "")}-${event.finalDate}`;
    if (!seen.has(key)) {
      seen.add(key);
      unique.push(event);
    }
  }

  return {
    month,
    searchedAt: new Date().toISOString(),
    sources: EVENT_SOURCES,
    errors,
    requiredMajorEvents: REQUIRED_MAJOR_EVENTS,
    events: unique,
  };
}
