fill.ts 44.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
/**
 * 补齐流程:每一格按「表内原有 → 地址解析 → 接口缓存 →(可选)邻近地点 → 地图接口」取值。
 *
 * 地址优先是这件事省钱的来源:第三方件只给 5 列(案件号 / 出险地点 / 报案时间 / 经度 / 纬度),
 * 三个目标列全空,旧判据「列空即查」等于每一行都付费。实测 42,806 行里
 * 行政区有 42,802 行第 3 段就写着、街道 16,333 行、道路 22,393 行明写在地址文本里 ——
 * 先读文本再查坐标,需付费的唯一坐标从 33,288 降到 17,421。
 *
 * 但「读得出」不等于「读得准」:地址解析与主程序逐行对齐,读出错词短语是它口径的一部分。
 * 所以每一格先过 targets.ts 里的 distrust 判据,读出来像顺口一句话的不采用、留给坐标去问
 * (用户口径:凡是不确定的都调 API)。坐标本来就问不了接口的行才回写可疑读法并标注需复核。
 */
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseAddress, splitParts, type ParsedAddress } from './address.ts';
import {
  Cache, QueryError, RequestCancelled, StopRun, text,
  type LookupClient, type ResultFields,
} from './client.ts';
import { insideSanityBox, normalizeCoordinates, toMicroDegrees, type Coords } from './coords.ts';
import { UserError } from './errors.ts';
import { createClient } from './key.ts';
import { NearbyIndex, type RefPoint } from './nearby.ts';
import { ADDRESS_ALIASES, CONSISTENCY_COLUMN, COORDINATE_COLUMNS, NEARBY_COLUMN, REVIEW_NOTE_COLUMN, SOURCES, STANDARD_ADDRESS_COLUMN, TARGETS, type NearbyField, type SourceName } from './targets.ts';
import { CONSISTENCY, DAPENG_STREETS, DAPENG_WRITTEN_DISTRICT, districtStreetConsistency, type Consistency } from './consistency.ts';
import {
  LIST_KINDS, buildRows, classify, listHeader, listPath, readOnlyList, type ListRow,
} from './lists.ts';
import { loadVocab, type Vocab } from './vocab.ts';
import { atomicCsv, validatePaths } from './csv-store.ts';
import { permuteTable, readTable, writeTable } from './table-store.ts';

/** 词表随工具一起走,不需要配置项;换城市就是换这一份 JSON */
export const DEFAULT_VOCAB = path.resolve(
  path.dirname(fileURLToPath(import.meta.url)), '..', 'config', 'shenzhen-districts.json',
);

const LOG_HEADERS_FIXED = [
  '原始记录号(含表头)', '输出行号(含表头)', '经度', '纬度', '请求经度', '请求纬度', '处理状态',
  ...TARGETS.flatMap((target) => [target.column, `${target.column}来源`]),
  '地址行政区', '地址街道', '地址道路',
  '接口行政区', '接口街道', '接口道路', '接口道路来源', '接口道路距离(米)', '道路候选(JSON)',
  '门牌道路', '门牌距离(米)', '邻近参照距离(米)', '备注', '失败或缺失原因',
];
export const LOG_HEADERS = LOG_HEADERS_FIXED;

export type Report = {
  exit_code: number;
  rows: number;
  /** 只靠表内原值 + 地址解析就补齐三项的行数(缓存与邻近补全的不算) */
  address_complete_rows: number;
  /** 本次完全没有触发接口调用的行数:原值 / 地址 / 缓存 / 邻近够用,或压根没轮到 */
  no_api_rows: number;
  /** 缓存与邻近都补完之后,真正进队列查询的唯一坐标数(付费上限) */
  lookup_coordinates: number;
  cache_hits: number;
  requests: number;
  /**
   * 本次把工具自己读错的行政区订正过来的行数:既有「地址写错、接口实测自洽」那一路,
   * 也有「接口给的区与本批分布相悖、按本批定」那一路。表内原有的区从不计入。
   */
  reconciled_rows: number;
  /** 接口与本批分布相悖、写了「复核提示」的行数(含只提示不改的行) */
  review_hint_rows: number;
  /** 由邻近参照点补上的行数(infer_nearby 关闭时恒为 0) */
  nearby_rows: number;
  /** 三个目标列按格统计的最终来源;界面用它说明哪些值是读出来的、哪些是查来的 */
  cells_by_source: Record<string, number>;
  /** 三个目标列里最终仍空白的格数 */
  blank_cells: number;
  statuses: Record<string, number>;
  /** 三份清单各自的行数;没有这类行就是 0,也不会生成文件 */
  list_rows: Record<string, number>;
  /** 三份清单的文件路径;只列出实际生成了的 */
  list_files: Record<string, string>;
  /** 「只跑清单里的行」本次匹配到的行数;没开这个开关时为 0 */
  only_list_rows: number;
  elapsed_seconds: number;
  stop_reason: string;
  output: string;
  log: string;
  cache: string;
};

/** 一件正在做的事;done/total 只在有明确进度可报时出现(调用接口那一档) */
export type Stage = { label: string; done?: number; total?: number };

/** 邻近推断半径覆盖(米);行政区不在这里,它一律不靠邻近补 */
export type NearbyRadii = { street?: number; road?: number };

export type RunOptions = {
  limit?: number | null;
  workers?: number;
  qps?: number;
  /** 用附近已知点的归属补空白;默认关闭,半径见 targets.ts */
  inferNearby?: boolean;
  /** 半径分档的临时改动,只为界面调参准备;不写就用 targets.ts 的分档 */
  nearbyMeters?: NearbyRadii;
  /** 三项仍有空白的记录整行排到末尾(在内存里定序,输出只写一次) */
  sortIncompleteLast?: boolean;
  /** 只跑清单里的行:这份清单之外的行本次不许问接口(给花费上锁,输出仍是完整表格) */
  onlyList?: string;
  /** 本轮的临时目录:处理日志与三份清单写在这里;不传就是源文件旁的 .temp */
  tempDir?: string;
  client?: LookupClient;
  /** 仅在确有待查坐标时调用;测试注入离线工厂以证明不访问网络。 */
  clientFactory?: (qps: number) => LookupClient | Promise<LookupClient>;
  progress?: (message: string) => void;
  /** 正在做哪一件事;图形界面用它显示进度,命令行不需要 */
  stage?: (stage: Stage) => void;
  signal?: AbortSignal;
  vocab?: Vocab;
};

type Plan = {
  status: string;
  reason: string;
  notes: string[];
  parsed: ParsedAddress;
  coords: Coords | null;
  /** 与 TARGETS 同下标;'' 表示这一格本次没有写入任何来源 */
  sources: (SourceName | '')[];
  /** 地址读出但不敢采用的格子,留给「坐标问不了接口」那类行兜底写入 */
  rejected: Array<{ index: number; value: string; reason: string }>;
  /** 本行坐标的接口/缓存答案,只为日志的「接口*」几列存在 */
  result: ResultFields | null;
  nearbyMeters: string;
  outputLine: number;
  /** 只跑清单里的行时,这一行不在清单上,本次没进队列 */
  skipped: boolean;
};

type Group = { coords: Coords; rows: number[] };

const EMPTY_PARSED: ParsedAddress = {
  district: '', street: '', road: '', rest: '', detail: '',
};

export async function runJob(input: string, output: string, cacheFile: string,
  options: RunOptions = {}): Promise<Report> {
  const limit = options.limit ?? null;
  const workers = options.workers ?? 20;
  const qps = options.qps ?? 100;
  const inferNearby = options.inferNearby ?? false;
  const radii = options.nearbyMeters ?? {};
  if (!Number.isInteger(workers) || workers <= 0) throw new UserError('workers 必须是正整数');
  if (limit !== null && (!Number.isInteger(limit) || limit <= 0)) throw new UserError('limit 必须是正整数');
  if (!Number.isFinite(qps) || qps < 0) throw new UserError('qps 必须是有限的非负数');
  for (const value of [radii.street, radii.road]) {
    if (value !== undefined && (!Number.isFinite(value) || value <= 0)) {
      throw new UserError('邻近半径必须是正数(米)');
    }
  }

  const vocab = options.vocab ?? loadVocab(DEFAULT_VOCAB);
  const source = path.resolve(input);
  const target = path.resolve(output);
  const cachePath = path.resolve(cacheFile);
  // 日志与清单是过程文件,统一进源文件旁的临时目录;输出目录只留正式表格
  const tempDir = path.resolve(options.tempDir
    ?? path.join(path.dirname(source), '.temp'));
  const logPath = validatePaths(source, target, cachePath, tempDir);
  options.stage?.({ label: '读取表格' });
  const table = readTable(source, limit);
  const { header, rows } = table;
  const column = new Map(header.map((name, position) => [name, position] as const));
  const at = (name: string): number => column.get(name) as number;
  const started = performance.now();
  if (table.appended.length > 0) {
    options.progress?.(`输入缺少 ${table.appended.join('、')} 列,已在末尾追加空列用于写入结果。`);
  }
  const addressColumn = ADDRESS_ALIASES.map((name) => column.get(name))
    .find((index) => index !== undefined);
  if (addressColumn === undefined) {
    options.progress?.(`输入没有「${ADDRESS_ALIASES[0]}」列,跳过地址解析,全部依赖坐标查询。`);
  }

  const plans: Plan[] = rows.map((_, position) => ({
    status: '未处理', reason: '', notes: [], parsed: EMPTY_PARSED, coords: null,
    sources: TARGETS.map(() => ''), rejected: [], result: null, nearbyMeters: '',
    outputLine: position + 2, skipped: false,
  }));
  const blanksOf = (position: number): number[] => TARGETS
    .map((_, index) => index)
    .filter((index) => text(rows[position][at(TARGETS[index].column)]) === '');

  // 只跑清单里的行:清单给的是行身份,不是新表 —— 仍然读原表、写完整表,只有清单内的行允许问接口
  // 留空是常态(不是「读当前目录」):先判空再 resolve
  const onlyGiven = (options.onlyList ?? '').trim();
  const onlyFile = onlyGiven === '' ? '' : path.resolve(onlyGiven);
  const only = onlyFile === '' ? null : readOnlyList(onlyFile);
  // 清单里有案件号、这份表里也有就按案件号匹配(重排过行也对得上),否则退回按原表行号
  const onlyColumn = only !== null && column.has(only.column) ? only.column : '原表行号';
  const onlyAt = only === null || onlyColumn === '原表行号' ? undefined : column.get(onlyColumn);
  const inList = (position: number): boolean => {
    if (only === null) return true;
    if (onlyColumn === '原表行号') return only.values.has(String(position + 2));
    return only.values.has(text(rows[position][onlyAt as number] ?? ''));
  };
  const matchedValues = new Set<string>();
  const onlyRows = only === null
    ? 0
    : rows.reduce((count, _, position) => {
      if (!inList(position)) return count;
      matchedValues.add(onlyColumn === '原表行号'
        ? String(position + 2)
        : text(rows[position][onlyAt as number] ?? ''));
      return count + 1;
    }, 0);
  if (only !== null && onlyRows === 0) {
    const pairing = `清单「${onlyFile}」里没有任何一行在这份表里找得到(按${onlyColumn}匹配)。`
      + '清单要与生成它的那份输入文件配对使用,表格被编辑过或换过文件就不要用它。';
    throw new UserError(limit === null ? pairing
      : `${pairing}这次还设了「只处理前几行」,表只读到第 ${limit} 行,清单里的行可能落在没读到的部分。`);
  }
  if (only !== null) {
    let notice = `只跑清单里的行:按「${onlyColumn}」匹配到 ${onlyRows} 行,`
      + '其余行只用地址与缓存,不会再问接口。';
    // 部分匹配时也要说清「还有几行没读到」:前 N 行之外的清单行这一轮根本没机会匹配,
    // 不说的话看着「匹配到 N 行」会以为清单跑全了,实际漏掉的那批还得再跑一次。
    if (limit !== null) {
      const unread = only.values.size - matchedValues.size;
      if (unread > 0) {
        notice += ` 清单里还有 ${unread} 行落在没读到的部分(这次只处理前 ${limit} 行),`
          + '去掉「只处理前几行」再跑才能覆盖它们。';
      }
    }
    options.progress?.(notice);
  }

  /** 只写空白格:已有值一律保留并记「表内原有」;写出来源,导入的人才知道哪些是免费的。 */
  const districtIndex = at(TARGETS[0].column);
  const streetIndex = at(TARGETS[1].column);
  const setCell = (position: number, index: number, value: string, from: SourceName): boolean => {
    if (text(rows[position][at(TARGETS[index].column)]) !== '') {
      if (plans[position].sources[index] === '') plans[position].sources[index] = SOURCES.original;
      return false;
    }
    if (value === '') return false;
    rows[position][at(TARGETS[index].column)] = value;
    plans[position].sources[index] = from;
    return true;
  };

  // 第一遍:表内原值 + 地址解析。坐标顺手规范化,完整行也留坐标 —— 邻近推断要拿它们当参照点
  options.stage?.({ label: '解析地址文本' });
  rows.forEach((row, position) => {
    const plan = plans[position];
    const addressText = addressColumn === undefined ? '' : text(row[addressColumn]);
    if (addressColumn !== undefined) plan.parsed = parseAddress(addressText, vocab);
    TARGETS.forEach((target_, index) => {
      setCell(position, index, text(row[at(target_.column)]), SOURCES.original);
      const fromText = target_.fromAddress(plan.parsed);
      if (fromText === '') return;
      // 读出来像顺口一句话的值不采用:这一格空着,让坐标去问接口(不确定的宁可花一次钱)
      const reason = target_.distrust?.(fromText, addressText, vocab) ?? '';
      if (reason === '') {
        setCell(position, index, fromText, SOURCES.address);
        return;
      }
      plan.rejected.push({ index, value: fromText, reason });
      plan.notes.push(`地址读出的${target_.column}「${fromText}」${reason},不采用,改用坐标查询`);
    });
    // 区没被采用(表内没写、或地址读出的区被可疑判据挡下)、但街道是地址原文读出来的:
    // 按词表里的街道属区补区。注意地址若整段没写区,解析阶段也认不出街道,这一补就不会触发 ——
    // 不为此放宽街道识别口径,否则「街道」本身就成了猜的,再拿它推区是双重猜测。
    // 只认这一遍刚写进去的地址街道 —— 接口街道后面才到,拿它推区等于绕一圈自证。
    if (text(rows[position][districtIndex]) === '' && plan.sources[1] === SOURCES.address) {
      const street = text(rows[position][streetIndex]);
      const owner = street === '' ? undefined : vocab.districtOfStreet.get(street);
      if (owner !== undefined) {
        setCell(position, 0, owner, SOURCES.streetDistrict);
        plan.notes.push(`地址未写行政区,按街道「${street}」属区补为「${owner}」`);
      }
    }
    plan.coords = safeCoordinates(row[at(COORDINATE_COLUMNS[0])], row[at(COORDINATE_COLUMNS[1])]);
  });

  // 只靠原值与地址就凑齐三项的行数:必须在查缓存/邻近之前定格。
  // 否则缓存命中或邻近推断补出来的行也会被算进来,「原值与地址即完整」就成了假话。
  const addressComplete = rows
    .reduce((count, _, position) => count + (blanksOf(position).length === 0 ? 1 : 0), 0);

  const groups = new Map<string, Group>();
  rows.forEach((_, position) => {
    if (blanksOf(position).length === 0) return;
    const coords = plans[position].coords;
    if (coords === null || !insideSanityBox(coords)) return; // 收尾时按无效坐标/域外坐标交代
    const key = `${coords[0]},${coords[1]}`;
    const group = groups.get(key);
    if (group === undefined) groups.set(key, { coords, rows: [position] });
    else group.rows.push(position);
  });

  const applyResult = (group: Group, result: ResultFields, from: SourceName): void => {
    for (const position of group.rows) {
      plans[position].result = result;
      TARGETS.forEach((target_, index) => {
        setCell(position, index, result[target_.api], from);
      });
    }
  };

  options.stage?.({ label: '查缓存' });
  const cache = new Cache(cachePath);
  let client = options.client;
  let stopped = false;
  let interrupted = false;
  let stopReason = '';
  let cachedGroups = 0;
  let nearbyRows = 0;
  let completed = 0;
  /** 真的走到 lookup 的行(同坐标多行共享一次调用,按整组记) */
  const apiRows = new Set<number>();
  let queued: Group[] = [];
  try {
    const uncached: Group[] = [];
    for (const group of groups.values()) {
      const result = cache.get(group.coords);
      if (result === null) uncached.push(group);
      else {
        applyResult(group, result, SOURCES.cache);
        cachedGroups += 1;
      }
    }

    if (inferNearby && uncached.length > 0) {
      options.stage?.({ label: '邻近推断' });
      nearbyRows = fillFromNearby(rows, plans, cache, blanksOf, column, setCell, radii);
    }

    // 邻近补完仍缺格的坐标才进队列;开了「只跑清单里的行」时,清单内的行才有资格排队
    queued = uncached.filter((group) => group.rows.some((position) => {
      if (blanksOf(position).length === 0) return false;
      if (inList(position)) return true;
      plans[position].skipped = true;
      return false;
    }));

    options.progress?.(`${table.sheet === null ? '' : `工作表 ${table.sheet.sheetName};`}`
      + `读取 ${rows.length} 行;原值与地址即完整 ${addressComplete} 行;`
      + `待查唯一坐标 ${queued.length};缓存命中 ${cachedGroups};邻近补全 ${nearbyRows} 行;`
      + `并发 ${workers};QPS ${qps === 0 ? '不限' : qps}`);
    if (queued.length > 0 && client === undefined) {
      // 先让人看见这一趟要问多少次,再去要 Key —— 付费的门槛前不能只写一句「请输入」
      options.stage?.({ label: '准备调用接口', total: queued.length });
      client = await (options.clientFactory ?? createClient)(qps);
    }
    if (queued.length > 0 && client !== undefined) {
      options.stage?.({ label: '调用地图接口', done: 0, total: queued.length });
      const active = client;
      const onAbort = (): void => {
        interrupted = true;
        stopped = true;
        stopReason = '用户中断';
        active.stopEvent.set();
      };
      if (options.signal !== undefined) {
        if (options.signal.aborted) onAbort();
        else options.signal.addEventListener('abort', onAbort, { once: true });
      }
      const queue = [...queued];
      const worker = async (): Promise<void> => {
        for (;;) {
          if (stopped) return;
          const group = queue.shift();
          if (group === undefined) return;
          for (const position of group.rows) apiRows.add(position);
          try {
            const result = await active.lookup(group.coords[0], group.coords[1]);
            cache.put(group.coords, result);
            applyResult(group, result, SOURCES.api);
          } catch (exc) {
            if (exc instanceof RequestCancelled) {
              // 运行已停止:保留已完成结果,该行留给收尾定成未处理。
            } else if (exc instanceof StopRun) {
              stopped = true;
              stopReason = exc.message;
              active.stopEvent.set();
              for (const position of group.rows) {
                plans[position].status = '请求失败';
                plans[position].reason = stopReason;
              }
            } else if (exc instanceof QueryError) {
              for (const position of group.rows) {
                plans[position].status = '请求失败';
                plans[position].reason = exc.message;
              }
            } else {
              throw exc;
            }
          }
          completed += 1;
          const drained = queue.length === 0;
          if (completed % 10 === 0 || drained) {
            options.stage?.({ label: '调用地图接口', done: completed, total: queued.length });
          }
          if (options.progress && (completed % 100 === 0 || drained)) {
            options.progress(`已处理唯一坐标 ${completed}/${queued.length},`
              + `耗时 ${((performance.now() - started) / 1000).toFixed(1)} 秒`);
          }
        }
      };
      try {
        await Promise.all(Array.from({ length: Math.min(workers, queued.length) }, () => worker()));
      } finally {
        options.signal?.removeEventListener('abort', onAbort);
      }
    }

    // 坐标问不了接口的行(无效坐标、域外坐标),可疑的文本读法仍比空白有用 ——
    // 写回去,但备注必须说清这一格没被接口复核过
    rows.forEach((_, position) => {
      const plan = plans[position];
      if (plan.rejected.length === 0) return;
      if (plan.coords !== null && insideSanityBox(plan.coords)) return;
      for (const item of plan.rejected) {
        const name = TARGETS[item.index].column;
        if (!setCell(position, item.index, item.value, SOURCES.address)) continue;
        plan.notes = plan.notes.filter((note) => !note.startsWith(`地址读出的${name}「${item.value}」`));
        plan.notes.push(`${name}「${item.value}」是可疑读法,但这一行的坐标问不了接口,先按地址写入,需复核`);
      }
    });

    // 区街道错配先做源头订正,再写判读列:错的是工具从地址读来的区名,街道反而是实测铁证
    const reconciledRows = reconcileDistricts(rows, plans, vocab, at);
    // 接口与本批分布相悖的另一路:区按本批分布定,街道/道路只提示不覆盖
    const { hints: reviewHintRows, corrections: batchCorrections } =
      annotateSourceConflicts(rows, plans, vocab, at);

    rows.forEach((_, position) => {
      conclude(plans[position], blanksOf(position), stopReason);
      const values = TARGETS.map((t) => text(rows[position][at(t.column)]));
      const consistency = annotate(plans[position], values, vocab);
      rows[position][at(CONSISTENCY_COLUMN)] = consistency;
      rows[position][at(STANDARD_ADDRESS_COLUMN)] =
        standardAddressOf(plans[position], rows[position], at, addressColumn);
    });

    const logPositions = rows.map((_, position) => position);
    if (options.sortIncompleteLast === true) {
      // 稳定排序:完整段与未完整段各自保持原顺序,整行一起搬;
      // 日志与输出行序一致(第 N 行对第 N 行),原始位置看「原始记录号」列
      logPositions.sort((a, b) => Number(blanksOf(a).length > 0) - Number(blanksOf(b).length > 0));
      logPositions.forEach((position, index) => { plans[position].outputLine = index + 2; });
      permuteTable(table, logPositions);
    }
    const logRows = logPositions.map((position) => logRow(rows[position], position, plans[position], column));
    options.stage?.({ label: '写出表格', total: rows.length });
    writeTable(target, table);
    options.stage?.({ label: '写出处理日志', total: rows.length });
    atomicCsv(logPath, LOG_HEADERS, logRows);

    // 三份清单:按处理状态、空白格数、备注分档,同一行只会进一份(限流优先,重跑就能解决的先说)
    const buckets = new Map<string, ListRow[]>();
    rows.forEach((_, position) => {
      const plan = plans[position];
      const blanks = blanksOf(position);
      const kind = classify(plan.status, blanks.length, plan.notes.length);
      if (kind === '') return;
      const list = buckets.get(kind) ?? [];
      list.push({
        values: rows[position], sourceLine: position + 2, outputLine: plan.outputLine,
        missing: blanks.map((index) => TARGETS[index].column).join('、'),
        status: plan.status, reason: plan.reason, notes: plan.notes.join(';'),
      });
      buckets.set(kind, list);
    });
    const listRows: Record<string, number> = {};
    const listFiles: Record<string, string> = {};
    for (const info of LIST_KINDS) listRows[info.title] = (buckets.get(info.kind) ?? []).length;
    const kinds = LIST_KINDS.filter((info) => (buckets.get(info.kind) ?? []).length > 0);
    if (kinds.length > 0) options.stage?.({ label: '写出本次清单', total: kinds.length });
    for (const info of kinds) {
      const list = buckets.get(info.kind) as ListRow[];
      const file = listPath(target, info, tempDir);
      atomicCsv(file, listHeader(header), buildRows(info, list));
      listFiles[info.title] = file;
    }

    const statuses: Record<string, number> = {};
    for (const plan of plans) statuses[plan.status] = (statuses[plan.status] ?? 0) + 1;
    const cellsBySource: Record<string, number> = {};
    let blankCells = 0;
    for (const plan of plans) {
      for (const source of plan.sources) {
        if (source === '') {
          blankCells += 1;
          continue;
        }
        cellsBySource[source] = (cellsBySource[source] ?? 0) + 1;
      }
    }
    const complete = plans.every((plan) => plan.status === '完整');
    return {
      exit_code: interrupted ? 130 : complete && !stopped ? 0 : 2,
      rows: rows.length,
      address_complete_rows: addressComplete,
      no_api_rows: rows.length - apiRows.size,
      lookup_coordinates: queued.length,
      cache_hits: cachedGroups,
      requests: client?.requests ?? 0,
      nearby_rows: nearbyRows,
      reconciled_rows: reconciledRows + batchCorrections,
      review_hint_rows: reviewHintRows,
      cells_by_source: cellsBySource,
      blank_cells: blankCells,
      statuses,
      list_rows: listRows,
      list_files: listFiles,
      only_list_rows: onlyRows,
      elapsed_seconds: (performance.now() - started) / 1000,
      stop_reason: stopReason,
      output: target,
      log: logPath,
      cache: cachePath,
    };
  } finally {
    if (client !== undefined) client.stopEvent.set();
    cache.close();
  }
}

function safeCoordinates(lngRaw: string, latRaw: string): Coords | null {
  try {
    return normalizeCoordinates(lngRaw, latRaw);
  } catch {
    return null;
  }
}

/** 收尾定状态。顺序讲究:已经付过钱失败的行,不能被后面的「坐标缺失」抢走说法。 */
/**
 * 把接口连写的 formatted_address 切成「省-市-区-街道-详细」五段,写法与「出险地点」一致。
 * 用四个锚点按顺序定位:省、市取自原「出险地点」前两段,区、街道取自接口 district/township;
 * 只在锚点确实出现在接口地址里时在其后补 '-',找不到就跳过,绝不硬切、不改动原文里的 '-'
 * (门牌号 10-3 号、POI 名 NEO-B 座里的连字符是地址内容,原样保留)。
 */
function dashifyApiAddress(api: string, province: string, city: string,
  district: string, township: string): string {
  // 省市从接口地址自身开头切,不依赖原「出险地点」(报案原文可能没写省市或写法异常)。
  // 只认「……省 + ……市」这种前缀(本批数据与接口返回均如此);认不出就跳过,
  // 再由下面区/街道锚点兜底,绝不把不确定的前缀硬切开。
  let out = api;
  const provinceMatch = /^(.+?省)(.+?市)/.exec(out);
  if (provinceMatch !== null) {
    const provinceEnd = provinceMatch[1].length;
    const cityEnd = provinceMatch[0].length;
    out = out.slice(0, provinceEnd) + '-' + out.slice(provinceEnd, cityEnd)
      + '-' + out.slice(cityEnd);
  }
  // 区、街道用接口字段当锚点;省市没从接口地址切出来时,退回原地址前两段补切。
  const anchors = [district, township].filter((value) => value !== '');
  if (provinceMatch === null && province !== '') anchors.unshift(province);
  if (provinceMatch === null && city !== '') anchors.unshift(city);
  for (const anchor of anchors) {
    const at = out.indexOf(anchor);
    if (at < 0) continue;
    const end = at + anchor.length;
    // 锚点已在段尾或后面已有 '-',不再补
    if (end >= out.length || out[end] === '-') continue;
    out = out.slice(0, end) + '-' + out.slice(end);
  }
  return out;
}

/**
 * 标准地址列:整列统一成「出险地点」的「省-市-区-街道-详细」分隔符风格。
 * 查过接口的:把接口 formatted_address 按省市(原地址前两段)+ 接口区/街道切成五段;
 * 没查接口的:用原地址省/市 + 最终区/街道/道路拼起来,同样带 '-'。
 * 原「出险地点」是报案原文,保持不动;门牌号里的 '-' 是地址内容,原样保留。
 */
function standardAddressOf(
  plan: Plan,
  row: readonly string[],
  at: (name: string) => number,
  addressColumn: number | undefined,
): string {
  const prefix = addressColumn === undefined ? [] : splitParts(text(row[addressColumn])).slice(0, 2);
  const tail = TARGETS.map((target) => text(row[at(target.column)])).filter((value) => value !== '');
  const api = text(plan.result?.formatted_address);
  if (api !== '') {
    const result = plan.result as ResultFields;
    return dashifyApiAddress(api, prefix[0] ?? '', prefix[1] ?? '',
      text(result.district), text(result.township));
  }
  return tail.length === 0 ? '' : [...prefix, ...tail].join('-');
}

function conclude(plan: Plan, blanks: number[], stopReason: string): void {
  const missing = blanks.map((index) => TARGETS[index].column).join('、');
  if (plan.status === '请求失败') {
    if (missing !== '') plan.notes.push(`仍缺 ${missing}`);
    return;
  }
  if (blanks.length === 0) {
    plan.status = '完整';
    plan.reason = '';
    return;
  }
  if (plan.coords === null) {
    plan.status = '无效坐标';
    plan.reason = `${COORDINATE_COLUMNS.join('/')} 缺失、非数值、格式非法或越界`;
    return;
  }
  if (!insideSanityBox(plan.coords)) {
    plan.status = '域外坐标';
    plan.reason = '坐标不在深圳合理范围内(主程序导入时同样会拒收),未查询';
    return;
  }
  if (plan.result !== null) {
    plan.status = '部分缺失';
    plan.reason = `接口未返回:${missing}`;
    return;
  }
  plan.status = '未处理';
  if (plan.skipped) {
    plan.reason = '不在本次清单里,这一行没问接口;去掉「只跑清单里的行」再跑就会查';
    return;
  }
  plan.reason = stopReason === '' ? '尚未查询,重跑可继续' : `${stopReason};重跑可继续`;
}

/**
 * 区街道错配的源头订正。实测 24 条真错配全是同一个模式:行政区来自地址解析、
 * 街道来自接口缓存,接口自己给的区与街道属区一致,只是与地址里写的区不同 ——
 * 换句话说,工具把两个源拼出了「宝安区 + 桃源街道」这种不存在的组合。
 *
 * 订正方向是改区、不是改街道:坐标反查的街道才是实测(龙井路就在南山区桃源街道),
 * 地址文本第 3 段的区名写错了。街道属区与接口返回区互相印证,证据比地址文本强。
 *
 * 六条闸门缺一不可,防止把别人的数据改掉:
 *   1. 行政区必须是工具自己从地址读来的(表内原有值属于原始数据,不擅自改写)
 *   2. 街道必须来自接口(api / cache),邻近推断的猜测不够格反过来订正区名
 *   3. 接口返回的街道与当前街道一致、返回的区等于街道属区(接口内部自洽)
 *   4. 当前区与街道确实判「不一致」,一致、大鹏单列、无判据的都不动
 *   5. 地图街道本身要有独立佐证,两条通道任一成立才动手:
 *      甲 本批数据里这个街道的区分布压倒性支持候选区(至少 5 行、占比不低于九成)
 *      乙 地址文本写的路名与地图接口返回的路名一致(坐标确实落在同一条路上)
 *    两通道都不成立时不订正,仍按「不一致」标注;宁可留给人看,也不拿可疑的地图值改区。
 *
 * 订正写进备注,原地址文本与日志里的「地址行政区」保持不变,留痕可追溯。
 */
/** 通道甲门槛:本批里同街道至少这么多行,且候选区占比不低于这个数,才算压倒性 */
const BATCH_STREET_MIN = 5;
const BATCH_STREET_SHARE = 0.9;

function reconcileDistricts(
  rows: string[][],
  plans: Plan[],
  vocab: Vocab,
  at: (name: string) => number,
): number {
  const districtIndex = at(TARGETS[0].column);
  const streetIndex = at(TARGETS[1].column);
  // 本批「街道 → 区」分布:订正前一次扫完。错配行只给它写错的那个区加一票,
  // 淹没在正确区里;小样本时正确区票数不够门槛,就自然退回通道乙判。
  const streetDistricts = new Map<string, Map<string, number>>();
  rows.forEach((row) => {
    const street = text(row[streetIndex]);
    const district = text(row[districtIndex]);
    if (street === '' || district === '') return;
    let counts = streetDistricts.get(street);
    if (counts === undefined) {
      counts = new Map();
      streetDistricts.set(street, counts);
    }
    counts.set(district, (counts.get(district) ?? 0) + 1);
  });

  let reconciled = 0;
  rows.forEach((_, position) => {
    const plan = plans[position];
    if (plan.result === null) return;
    if (plan.sources[0] !== SOURCES.address) return;
    if (plan.sources[1] !== SOURCES.api && plan.sources[1] !== SOURCES.cache) return;
    const district = text(rows[position][districtIndex]);
    const street = text(rows[position][streetIndex]);
    if (district === '' || street === '') return;
    if (districtStreetConsistency(district, street, vocab) !== CONSISTENCY.different) return;
    const apiDistrict = text(plan.result.district);
    if (apiDistrict === '' || text(plan.result.township) !== street) return;
    if (vocab.districtOfStreet.get(street) !== apiDistrict) return;

    // 独立佐证:甲看本批众数,乙看地址路名与实测路名是否同一条
    const counts = streetDistricts.get(street);
    const candidateCount = counts?.get(apiDistrict) ?? 0;
    const total = counts === undefined
      ? 0 : [...counts.values()].reduce((sum, n) => sum + n, 0);
    const byBatch = candidateCount >= BATCH_STREET_MIN
      && candidateCount / total >= BATCH_STREET_SHARE;
    const addressRoad = text(plan.parsed.road);
    const byRoad = addressRoad !== '' && addressRoad === text(plan.result.road);
    if (!byBatch && !byRoad) return;

    rows[position][districtIndex] = apiDistrict;
    plan.sources[0] = plan.sources[1];
    plan.notes.push(`地址所写「${district}」与实测坐标不符,行政区按实测订正为「${apiDistrict}」`);
    plan.notes.push(byBatch && byRoad
      ? `订正依据:本批 ${candidateCount}/${total} 行属${apiDistrict},地址路名「${addressRoad}」与实测一致`
      : byBatch
        ? `订正依据:本批 ${candidateCount}/${total} 行属${apiDistrict}`
        : `订正依据:地址路名「${addressRoad}」与实测一致`);
    reconciled += 1;
  });
  return reconciled;
}

/**
 * 接口返回与本批分布相悖:区按本批分布定,街道/道路只提示不覆盖。
 *
 * 为什么要分两种处置:街道是行政单元,一个街道只属一个区,「街道→区」分布经词表固化后
 * 可以当裁判;道路不是 —— 北环大道跨梅林/华富/桃源,深南中路跨福田/华强北,
 * 真表里 5,518 行「接口街道 ≠ 该路名主街道」绝大多数是长路跨街道,按分布覆盖会造错案。
 *
 * 区这一路也不是接口说什么就改什么:接口区与街道属区相悖时,以本批分布(词表)为准。
 * 两条独立佐证仍缺一不可 —— 本批该街道的区分布压倒性支持属区,或地址路名与接口路名一致。
 * 表内原有的区一律不改写,只写提示交人工判断。
 *
 * 提示写进「复核提示」列(给人看),同时进备注与待复核清单(让导入时看得见),
 * 但不参与任何自动剔除,也不改「区街道一致性」的判定 —— 那是标注事实,不是来源冲突。
 */
function annotateSourceConflicts(
  rows: string[][],
  plans: Plan[],
  vocab: Vocab,
  at: (name: string) => number,
): { hints: number; corrections: number } {
  const districtIndex = at(TARGETS[0].column);
  const streetIndex = at(TARGETS[1].column);
  const roadIndex = at(TARGETS[2].column);
  const reviewIndex = at(REVIEW_NOTE_COLUMN);
  const bump = (map: Map<string, Map<string, number>>, key: string, value: string) => {
    let counts = map.get(key);
    if (counts === undefined) {
      counts = new Map();
      map.set(key, counts);
    }
    counts.set(value, (counts.get(value) ?? 0) + 1);
  };
  const totalOf = (counts: Map<string, number> | undefined) =>
    counts === undefined ? 0 : [...counts.values()].reduce((sum, n) => sum + n, 0);

  // 本批「街道 → 区」「道路 → 街道」两张分布,扫一遍就够
  const streetDistricts = new Map<string, Map<string, number>>();
  const roadStreets = new Map<string, Map<string, number>>();
  rows.forEach((row) => {
    const street = text(row[streetIndex]);
    const district = text(row[districtIndex]);
    const road = text(row[roadIndex]);
    if (street !== '' && district !== '') bump(streetDistricts, street, district);
    if (road !== '' && street !== '') bump(roadStreets, road, street);
  });

  let hints = 0;
  let corrections = 0;
  rows.forEach((_, position) => {
    const plan = plans[position];
    if (plan.result === null) return;
    const apiDistrict = text(plan.result.district);
    const apiStreet = text(plan.result.township);
    const apiRoad = text(plan.result.road);
    const district = text(rows[position][districtIndex]);
    const street = text(rows[position][streetIndex]);
    const road = text(rows[position][roadIndex]);
    const owner = vocab.districtOfStreet.get(street);
    const addressRoad = text(plan.parsed.road);
    const notes: string[] = [];

    // ① 区:接口区与本批「街道属区」相悖。大鹏三街道是业务单列,不算冲突。
    if (
      owner !== undefined && apiDistrict !== '' && apiDistrict !== owner
      && district !== '' && district !== owner
      && !(DAPENG_STREETS.has(street) && district === DAPENG_WRITTEN_DISTRICT)
    ) {
      const counts = streetDistricts.get(street);
      const ownerCount = counts?.get(owner) ?? 0;
      const total = totalOf(counts);
      const byBatch = ownerCount >= BATCH_STREET_MIN
        && ownerCount / total >= BATCH_STREET_SHARE;
      const byRoad = addressRoad !== '' && addressRoad === apiRoad;
      if (byBatch || byRoad) {
        // 只有工具自己从地址读来的区可改;表内原有值是交付方的数据,只提示
        const fromAddress = plan.sources[0] === SOURCES.address;
        if (fromAddress) {
          rows[position][districtIndex] = owner;
          plan.sources[0] = SOURCES.batch;
          corrections += 1;
        }
        notes.push(
          `接口返回「${apiDistrict} · ${apiStreet || '?'} · ${apiRoad || '?'}」与本批分布不符;`
          + `本批${street}属${owner}${byBatch ? `(${ownerCount}/${total})` : ''};`
          + (fromAddress
            ? `行政区已按本批定为「${owner}」,街道/道路未改`
            : `行政区为表内原有值「${district}」未改`)
          + ';请人工复核',
        );
        plan.notes.push(`来源冲突:${notes.at(-1)}`);
      }
    }

    // ② 街道/道路:接口街道与本批路名主街道相悖,只提示不覆盖。
    // 强门槛(≥5 行且九成集中)压掉长路跨街道的噪声;即便如此也只是「请复核」,不是判错。
    if (apiStreet !== '' && street !== '') {
      const roadKey = road !== '' ? road : addressRoad;
      const counts = roadStreets.get(roadKey);
      if (counts !== undefined && counts.size >= 2) {
        const total = totalOf(counts);
        const [topStreet, topCount] = [...counts].sort((a, b) => b[1] - a[1])[0];
        if (
          topStreet !== apiStreet && topCount >= BATCH_STREET_MIN
          && topCount / total >= BATCH_STREET_SHARE
        ) {
          notes.push(
            `接口返回「${apiDistrict || '?'} · ${apiStreet} · ${apiRoad || '?'}」与本批分布不符;`
            + `本批「${roadKey}」${topCount}/${total} 行落在「${topStreet}」;`
            + `街道/道路未改(路名可能跨街道,仅供参考);请人工复核`,
          );
          plan.notes.push(`来源冲突:${notes.at(-1)}`);
        }
      }
    }

    if (notes.length === 0) return;
    const previous = text(rows[position][reviewIndex]);
    rows[position][reviewIndex] = previous === ''
      ? notes.join(';')
      : `${previous};${notes.join(';')}`;
    hints += 1;
  });
  return { hints, corrections };
}

/**
 * 值得复核、但不改动取值的事实写进备注:导入的人会照着备注抽样核对,而不是照着状态猜。
 * 邻市的结果照实写进列(业务要看真名),所以这里只补一句「不在深圳辖区名单内」。
 *
 * 区街道一致性同时写两处:备注里写人话(带属区与行政区两个值),
 * 「区街道一致性」列写结构化的五档结论,供主程序导入时直接读、不必重造词表。
 * 大鹏三街道挂龙岗不算错配(判定见 consistency.ts),两处都不写分歧。
 */
function annotate(plan: Plan, values: string[], vocab: Vocab): Consistency {
  const [district, street] = values;
  if (district !== '' && !vocab.shenzhen.has(district)) {
    plan.notes.push(`行政区「${district}」不在深圳辖区名单内`);
  }
  const consistency = districtStreetConsistency(district, street, vocab);
  if (consistency === CONSISTENCY.different) {
    const owner = vocab.districtOfStreet.get(street) ?? '?';
    plan.notes.push(`街道「${street}」属${owner},与行政区「${district}」不一致`);
  }
  return consistency;
}

/** 参照点一:本批里三项都已定、坐标可用的行;参照点二:缓存里已查过的坐标。 */
function buildRefs(
  rows: string[][],
  plans: Plan[],
  blanksOf: (position: number) => number[],
  column: Map<string, number>,
  cache: Cache,
): RefPoint[] {
  const refs: RefPoint[] = [];
  rows.forEach((_, position) => {
    const plan = plans[position];
    if (plan.coords === null || blanksOf(position).length > 0) return;
    if (!insideSanityBox(plan.coords)) return;
    const value = (field: NearbyField): string =>
      text(rows[position][column.get(NEARBY_COLUMN[field]) as number]);
    refs.push({
      lng: toMicroDegrees(plan.coords[0]), lat: toMicroDegrees(plan.coords[1]),
      district: value('district'), street: value('street'), road: value('road'),
    });
  });
  for (const point of cache.points()) {
    refs.push({
      lng: point.lng, lat: point.lat,
      district: point.district, street: point.township, road: point.road,
    });
  }
  return refs;
}

/**
 * 邻近推断:半径按字段分档(见 targets.ts),参照点的区与本行已知的区不一致时不用 ——
 * 邻近只回答「这一带归哪个街道」,不能把案件记到隔壁区头上。
 */
function fillFromNearby(
  rows: string[][],
  plans: Plan[],
  cache: Cache,
  blanksOf: (position: number) => number[],
  column: Map<string, number>,
  setCell: (position: number, index: number, value: string, from: SourceName) => boolean,
  radii: NearbyRadii,
): number {
  const index = new NearbyIndex(buildRefs(rows, plans, blanksOf, column, cache));
  let filledRows = 0;
  rows.forEach((_, position) => {
    const plan = plans[position];
    if (plan.coords === null) return;
    const blanks = blanksOf(position);
    if (blanks.length === 0) return;
    const lng = toMicroDegrees(plan.coords[0]);
    const lat = toMicroDegrees(plan.coords[1]);
    const knownDistrict = text(rows[position][column.get(NEARBY_COLUMN.district) as number]);
    let meters = 0;
    for (const target_ of blanks) {
      const field = TARGETS[target_].nearby;
      // 行政区这一档没有半径可改:邻近点跨区太容易,界面上也不给这一栏
      const radius = field === 'district' ? 0 : radii[field] ?? TARGETS[target_].inferMeters;
      if (radius <= 0) continue;
      const hit = index.nearest(lng, lat, radius, (point) => {
        if (point[field] === '') return false;
        return knownDistrict === '' || point.district === '' || point.district === knownDistrict;
      });
      if (hit === null) continue;
      if (setCell(position, target_, hit.point[field], SOURCES.nearby)) {
        meters = Math.max(meters, Math.round(hit.meters));
      }
    }
    if (meters > 0) {
      plan.nearbyMeters = String(meters);
      filledRows += 1;
    }
  });
  return filledRows;
}

function logRow(row: string[], position: number, plan: Plan, column: Map<string, number>): string[] {
  const result = plan.result;
  const value = (index: number): string => row[column.get(TARGETS[index].column) as number];
  return [
    String(position + 2), String(plan.outputLine),
    row[column.get(COORDINATE_COLUMNS[0]) as number], row[column.get(COORDINATE_COLUMNS[1]) as number],
    plan.coords === null ? '' : plan.coords[0], plan.coords === null ? '' : plan.coords[1],
    plan.status,
    ...TARGETS.flatMap((_, index) => [value(index), plan.sources[index]]),
    plan.parsed.district, plan.parsed.street, plan.parsed.road,
    result?.district ?? '', result?.township ?? '', result?.road ?? '',
    result?.road_source ?? '', result?.road_distance ?? '',
    JSON.stringify(result?.candidates ?? []),
    result?.street_road ?? '', result?.street_distance ?? '',
    plan.nearbyMeters, plan.notes.join(';'), plan.reason,
  ];
}