import type { RouteByPatternOp, RouteRule } from '../transforms.schema';
import type { Row } from '../row';

/**
 * route_by_pattern — 一份 input → N 份 output(按字段值规则分流)。
 *
 * routes 顺序匹配,第一个命中规则的 row 入对应 output 表。
 * 都没命中:
 *   - 有 `default: true` 的兜底分支 → 进对应 output
 *   - 没兜底 → 丢弃,跑完一轮后产 dropped 计数(由 engine 落 log)
 *
 * 返回:Record<outputTableName, Row[]> + dropped 计数
 */
export function runRouteByPattern(
  op: RouteByPatternOp,
  rows: Row[],
): { outputs: Record<string, Row[]>; dropped: number } {
  const outputs: Record<string, Row[]> = {};
  for (const r of op.routes) {
    outputs[r.output] = [];
  }
  let dropped = 0;

  for (const row of rows) {
    const v = row[op.field];
    const vStr = v === null || v === undefined ? '' : String(v);
    let matched = false;
    for (const route of op.routes) {
      if (testRule(vStr, route.when)) {
        outputs[route.output]!.push(row);
        matched = true;
        break;
      }
    }
    if (!matched) dropped++;
  }

  return { outputs, dropped };
}

function testRule(value: string, rule: RouteRule): boolean {
  if ('default' in rule) return rule.default === true;
  if ('starts_with' in rule) return rule.starts_with.some((p) => value.startsWith(p));
  if ('equals' in rule) return rule.equals.some((p) => value === p);
  if ('contains' in rule) return rule.contains.some((p) => value.includes(p));
  if ('in' in rule) return rule.in.some((p) => value === p);
  return false;
}
