xyc
2026-11-11 d5ca840e64d444705a83df9e393c5df9e085feff
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Inspect raw vehicle track points against enterprise ledger routes."""
 
from __future__ import annotations
 
import argparse
import calendar
import hashlib
import json
import math
import re
import struct
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from datetime import date, datetime
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
 
import sys
 
 
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))
 
from tools.enterprise_ledger_inspection import (  # noqa: E402
    PROFILES,
    aggregate_ledger,
    aggregate_tracks,
    canonical_plate,
    parse_ledger,
    parse_track_summary,
)
 
 
@dataclass(frozen=True)
class Endpoint:
    label: str
    aliases: Tuple[str, ...]
    strict: bool = True
 
 
@dataclass(frozen=True)
class VehicleSpec:
    profile_key: str
    plate: str
    directory: str
    endpoints: Tuple[Endpoint, ...] = ()
    unresolved_route_terms: Tuple[str, ...] = ()
 
 
SELECTED_VEHICLES: Tuple[VehicleSpec, ...] = (
    VehicleSpec(
        "anxin",
        "\u9102L1N523",
        "\u54b8\u5b81/\u5b89\u6b23",
        (
            Endpoint("\u54b8\u5b81", ("\u54b8\u5b81",)),
            Endpoint("\u5929\u6d25", ("\u5929\u6d25",)),
            Endpoint("\u5d07\u9633", ("\u5d07\u9633",)),
        ),
    ),
    VehicleSpec(
        "demin",
        "\u9102L1J689",
        "\u54b8\u5b81/\u5fb7\u654f",
        (
            Endpoint("\u60e0\u5dde", ("\u60e0\u5dde",)),
            Endpoint("\u6c5f\u95e8", ("\u6c5f\u95e8",)),
            Endpoint("\u4f5b\u5c71", ("\u4f5b\u5c71",)),
        ),
    ),
    VehicleSpec(
        "datong",
        "\u9102J20052D",
        "\u9ec4\u5188/\u5927\u901a",
        (Endpoint("\u6d60\u6c34", ("\u6d60\u6c34",)),),
    ),
    VehicleSpec(
        "huinong",
        "\u9102LH832D",
        "\u54b8\u5b81/\u60e0\u4fac",
        (
            Endpoint("\u54b8\u5b81", ("\u54b8\u5b81",)),
            Endpoint("\u6f5c\u6c5f", ("\u6f5c\u6c5f",)),
        ),
    ),
    VehicleSpec(
        "luchang",
        "\u9102L53508",
        "\u54b8\u5b81/\u8def\u7545\u901a",
        (
            Endpoint("\u901a\u57ce", ("\u901a\u57ce",)),
            Endpoint("\u9ec4\u9f99", ("\u9ec4\u9f99",), False),
        ),
    ),
    VehicleSpec(
        "guangfa",
        "\u9102J50898",
        "\u9ec4\u5188/\u5e7f\u53d1",
        (
            Endpoint("\u9ec4\u6885", ("\u9ec4\u6885",)),
            Endpoint("\u4e49\u4e4c", ("\u4e49\u4e4c",)),
        ),
    ),
    VehicleSpec(
        "kaiying",
        "\u9102J0C916",
        "\u9ec4\u5188/\u51ef\u8d62",
        unresolved_route_terms=("\u5b89\u9053\u9ea6", "\u946b\u745e\u666f"),
    ),
    VehicleSpec(
        "xindafei",
        "\u9102J21646D",
        "\u9ec4\u5188/\u946b\u8fbe\u98de",
        (
            Endpoint("\u9ec4\u5dde", ("\u9ec4\u5dde",)),
            Endpoint("\u76d0\u57ce", ("\u76d0\u57ce",)),
        ),
    ),
    VehicleSpec(
        "shengda",
        "\u9102E19507",
        "\u5b9c\u660c/\u665f\u8fbe",
        (
            Endpoint("\u5408\u80a5", ("\u5408\u80a5",)),
            Endpoint("\u6b66\u6c49", ("\u6b66\u6c49",)),
            Endpoint("\u5b9c\u660c", ("\u5b9c\u660c",)),
        ),
        ("\u5174\u798f\u7535\u5b50", "\u8054\u4ed5(\u6e56\u5317)\u65b0\u6750\u6599"),
    ),
    VehicleSpec(
        "heyun",
        "\u9102E69878",
        "\u5b9c\u660c/\u8a38\u8fd0",
        (
            Endpoint("\u679d\u6c5f", ("\u679d\u6c5f",)),
            Endpoint("\u5949\u8282", ("\u5949\u8282",)),
        ),
    ),
    VehicleSpec(
        "kaixiangda",
        "\u9102E68056",
        "\u5b9c\u660c/\u51ef\u7965\u8fbe",
        (
            Endpoint("\u7307\u4ead", ("\u7307\u4ead",)),
            Endpoint("\u5317\u6d77", ("\u5317\u6d77",)),
            Endpoint("\u6d59\u6c5f", ("\u6d59\u6c5f", "\u5609\u5174")),
        ),
    ),
    VehicleSpec(
        "minkun",
        "\u9102E36292",
        "\u5b9c\u660c/\u6c11\u5764",
        unresolved_route_terms=("\u5408\u76ca\u8def", "\u5927\u6811\u6e7e"),
    ),
)
 
 
@dataclass
class Cell:
    row: int
    col: int
    value: Any
 
 
@dataclass
class TrackPoint:
    timestamp: datetime
    longitude: float
    latitude: float
    speed: float
    speed_text: str
    status: str
    alarm: str
    location: str
    province: str
    prefecture: str
    county: str
    company: str
    plate: str
    plate_no_raw: str
    source_file: str
    receive_time: Optional[datetime] = None
    operator: str = ""
    source_path: str = ""
    source_path_hash: str = ""
    source_row: int = 0
 
 
@dataclass
class FileAudit:
    path: str
    sha256: str
    row_count: int
    valid_point_count: int
    first_time: Optional[datetime] = None
    last_time: Optional[datetime] = None
    plates: Counter = field(default_factory=Counter)
    companies: Counter = field(default_factory=Counter)
    segment_no: int = 0
    segment_start_date: Optional[date] = None
    segment_end_date: Optional[date] = None
 
    def to_dict(self) -> Dict[str, Any]:
        return {
            "path": self.path,
            "sha256": self.sha256,
            "row_count": self.row_count,
            "valid_point_count": self.valid_point_count,
            "first_time": self.first_time.isoformat(sep=" ") if self.first_time else None,
            "last_time": self.last_time.isoformat(sep=" ") if self.last_time else None,
            "plates": dict(self.plates),
            "companies": dict(self.companies),
            "segment_no": self.segment_no,
            "segment_start_date": str(self.segment_start_date) if self.segment_start_date else None,
            "segment_end_date": str(self.segment_end_date) if self.segment_end_date else None,
        }
 
 
def read_records(data: bytes) -> Iterable[Tuple[int, bytes]]:
    position = 0
    size = len(data)
    while position + 4 <= size:
        record_type, record_length = struct.unpack_from("<HH", data, position)
        position += 4
        payload = data[position:position + record_length]
        if len(payload) != record_length:
            raise ValueError(
                "Truncated record at %d: type 0x%04x expected %d got %d"
                % (position - 4, record_type, record_length, len(payload))
            )
        position += record_length
        yield record_type, payload
 
 
def parse_label(payload: bytes) -> Optional[Cell]:
    if len(payload) < 8:
        return None
    row, col = struct.unpack_from("<HH", payload, 0)
    text_length = payload[7]
    raw = payload[8:8 + text_length]
    if len(raw) != text_length:
        return None
    try:
        value = raw.decode("gbk")
    except UnicodeDecodeError:
        value = raw.decode("latin1")
    return Cell(row, col, value)
 
 
def parse_number(payload: bytes) -> Optional[Cell]:
    if len(payload) != 15:
        return None
    row, col = struct.unpack_from("<HH", payload, 0)
    value = struct.unpack_from("<d", payload, 7)[0]
    return Cell(row, col, value)
 
 
def parse_integer(payload: bytes) -> Optional[Cell]:
    if len(payload) != 9:
        return None
    row, col = struct.unpack_from("<HH", payload, 0)
    value = struct.unpack_from("<H", payload, 7)[0]
    return Cell(row, col, value)
 
 
def read_cells(path: Path) -> List[Cell]:
    data = path.read_bytes()
    cells: List[Cell] = []
    for record_type, payload in read_records(data):
        cell = None
        if record_type == 0x0004:
            cell = parse_label(payload)
        elif record_type == 0x0003:
            cell = parse_number(payload)
        elif record_type == 0x0002:
            cell = parse_integer(payload)
        if cell is not None:
            cells.append(cell)
    return cells
 
 
def table_from_cells(cells: Sequence[Cell]) -> List[Dict[int, Any]]:
    by_row: Dict[int, Dict[int, Any]] = defaultdict(dict)
    for cell in cells:
        by_row[cell.row][cell.col] = cell.value
    max_row = max(by_row, default=-1)
    return [by_row.get(row, {}) for row in range(max_row + 1)]
 
 
SEGMENT_DATE_RE = re.compile(
    "(\\d{2})\u5e74(\\d{1,2})\u6708(\\d{1,2})\u65e5.*?"
    "(\\d{2})\u5e74(\\d{1,2})\u6708(\\d{1,2})\u65e5"
)
 
 
def parse_timestamp(value: Any) -> datetime:
    return datetime.strptime(str(value), "%y-%m-%d %H:%M:%S")
 
 
def parse_timestamp_optional(value: Any) -> Optional[datetime]:
    try:
        return parse_timestamp(value)
    except (TypeError, ValueError):
        return None
 
 
def parse_segment_dates(path: Path, period: str) -> Tuple[Optional[date], Optional[date]]:
    match = SEGMENT_DATE_RE.search(path.name)
    if not match:
        return None, None
    try:
        return (
            date(2000 + int(match.group(1)), int(match.group(2)), int(match.group(3))),
            date(2000 + int(match.group(4)), int(match.group(5)), int(match.group(6))),
        )
    except ValueError:
        return None, None
 
 
def segment_sort_key(path: Path, period: str) -> Tuple[date, str]:
    start, _ = parse_segment_dates(path, period)
    fallback = date(9999, 12, 31)
    return (start or fallback, path.name)
 
 
def parse_speed(value: Any) -> float:
    text = str(value or "0km/h").lower().replace("km/h", "").strip()
    try:
        return float(text)
    except ValueError:
        return 0.0
 
 
def split_location(value: Any) -> Tuple[str, str, str]:
    parts = [part.strip() for part in str(value or "").replace("/", ",").split(",") if part.strip()]
    province = parts[0] if parts else ""
    prefecture = parts[1] if len(parts) > 1 else ""
    county = parts[2] if len(parts) > 2 else ""
    return province, prefecture, county
 
 
def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for block in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()
 
 
def haversine_km(a: TrackPoint, b: TrackPoint) -> float:
    radius_km = 6371.0088
    lat1 = math.radians(a.latitude)
    lat2 = math.radians(b.latitude)
    dlat = lat2 - lat1
    dlon = math.radians(b.longitude - a.longitude)
    h = (
        math.sin(dlat / 2.0) ** 2
        + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2.0) ** 2
    )
    return 2.0 * radius_km * math.asin(min(1.0, math.sqrt(h)))
 
 
def load_track_points(spec: VehicleSpec, work_root: Path, period: str) -> Tuple[List[TrackPoint], List[FileAudit]]:
    directory = work_root / spec.directory
    paths = sorted(directory.glob("*%s*.xls" % spec.plate[1:]), key=lambda item: segment_sort_key(item, period))
    if not paths:
        raise RuntimeError("No track point files found for %s in %s" % (spec.plate, directory))
 
    points: List[TrackPoint] = []
    audits: List[FileAudit] = []
    for segment_no, path in enumerate(paths, start=1):
        cells = read_cells(path)
        rows = table_from_cells(cells)
        segment_start_date, segment_end_date = parse_segment_dates(path, period)
        audit = FileAudit(
            str(path), sha256_file(path), max(0, len(rows) - 1), 0,
            segment_no=segment_no,
            segment_start_date=segment_start_date,
            segment_end_date=segment_end_date,
        )
        path_hash = hashlib.sha256(str(path.resolve()).casefold().encode("utf-8")).hexdigest()
        seen_header = False
        for source_row, row in enumerate(rows, start=1):
            if not seen_header and str(row.get(0, "")) == "\u5355\u4f4d\u540d\u79f0":
                seen_header = True
                continue
            if not seen_header or not all(col in row for col in (2, 4, 5)):
                continue
            company = str(row.get(0, "")).strip()
            raw_plate_text = str(row.get(1, "")).strip()
            raw_plate = canonical_plate(raw_plate_text)
            audit.plates[raw_plate] += 1
            audit.companies[company] += 1
            if raw_plate != spec.plate:
                continue
            try:
                timestamp = parse_timestamp(row[2])
                longitude = float(row[4])
                latitude = float(row[5])
            except (TypeError, ValueError):
                continue
            if not (-180 <= longitude <= 180 and -90 <= latitude <= 90):
                continue
            if longitude == 0 or latitude == 0:
                continue
            province, prefecture, county = split_location(row.get(10, ""))
            point = TrackPoint(
                timestamp=timestamp,
                longitude=longitude,
                latitude=latitude,
                speed=parse_speed(row.get(6)),
                speed_text=str(row.get(6, "")).strip(),
                status=str(row.get(7, "")),
                alarm=str(row.get(8, "")),
                location=str(row.get(10, "")),
                province=province,
                prefecture=prefecture,
                county=county,
                company=company,
                plate=raw_plate,
                plate_no_raw=raw_plate_text,
                source_file=path.name,
                receive_time=parse_timestamp_optional(row.get(3)),
                operator=str(row.get(9, "")).strip(),
                source_path=str(path),
                source_path_hash=path_hash,
                source_row=source_row,
            )
            points.append(point)
            audit.valid_point_count += 1
            if audit.first_time is None or timestamp < audit.first_time:
                audit.first_time = timestamp
            if audit.last_time is None or timestamp > audit.last_time:
                audit.last_time = timestamp
        audits.append(audit)
 
    points.sort(key=lambda point: (point.timestamp, point.longitude, point.latitude))
    return points, audits
 
 
def deduplicate_points(points: Sequence[TrackPoint]) -> List[TrackPoint]:
    seen = set()
    result: List[TrackPoint] = []
    for point in points:
        key = (
            point.timestamp,
            round(point.longitude, 6),
            round(point.latitude, 6),
            point.status,
            point.location,
        )
        if key in seen:
            continue
        seen.add(key)
        result.append(point)
    return result
 
 
def point_distance_stats(points: Sequence[TrackPoint]) -> Dict[str, Any]:
    raw_distance = 0.0
    clean_distance = 0.0
    clean_steps = 0
    rejected_time_gap = 0
    rejected_speed = 0
    daily_distance: Dict[str, float] = defaultdict(float)
    for start, end in zip(points, points[1:]):
        distance = haversine_km(start, end)
        raw_distance += distance
        seconds = (end.timestamp - start.timestamp).total_seconds()
        if seconds <= 0 or seconds > 900:
            rejected_time_gap += 1
            continue
        speed = distance / (seconds / 3600.0)
        if speed > 120:
            rejected_speed += 1
            continue
        clean_distance += distance
        clean_steps += 1
        daily_distance[end.timestamp.date().isoformat()] += distance
    moving_days = sorted(day for day, distance in daily_distance.items() if distance >= 1.0)
    return {
        "raw_distance": raw_distance,
        "clean_distance": clean_distance,
        "clean_steps": clean_steps,
        "rejected_time_gap": rejected_time_gap,
        "rejected_speed": rejected_speed,
        "daily_distance": dict(sorted(daily_distance.items())),
        "moving_days": moving_days,
    }
 
 
def top_counter(counter: Counter, limit: int = 8) -> List[Tuple[str, int]]:
    return [(name, count) for name, count in counter.most_common(limit) if name]
 
 
def endpoint_stats(points: Sequence[TrackPoint], endpoints: Sequence[Endpoint]) -> List[Dict[str, Any]]:
    result = []
    for endpoint in endpoints:
        matching = [
            point for point in points
            if any(alias in point.location for alias in endpoint.aliases)
        ]
        result.append({
            "label": endpoint.label,
            "aliases": list(endpoint.aliases),
            "strict": endpoint.strict,
            "point_count": len(matching),
            "day_count": len({point.timestamp.date() for point in matching}),
            "first_time": min((point.timestamp for point in matching), default=None),
            "last_time": max((point.timestamp for point in matching), default=None),
        })
    return result
 
 
def route_group_stats(ledger_rows: Sequence[Any]) -> List[Dict[str, Any]]:
    grouped: Dict[str, Dict[str, Any]] = {}
    for row in ledger_rows:
        key = row.route or "(blank)"
        item = grouped.setdefault(key, {
            "route": row.route,
            "cargo_types": set(),
            "rows": 0,
            "trips": 0.0,
            "mileage": 0.0,
            "freight": 0.0,
            "turnover": 0.0,
        })
        item["rows"] += 1
        item["trips"] += row.trips or 0.0
        item["mileage"] += row.total_mileage or 0.0
        item["freight"] += row.freight or 0.0
        item["turnover"] += row.turnover or 0.0
        if row.cargo_type:
            item["cargo_types"].add(row.cargo_type)
    result = []
    for item in grouped.values():
        item["cargo_types"] = sorted(item["cargo_types"])
        result.append(item)
    return sorted(result, key=lambda item: (-item["mileage"], item["route"]))
 
 
def safe_rate(numerator: Optional[float], denominator: Optional[float]) -> Optional[float]:
    if numerator is None or denominator in (None, 0):
        return None
    return numerator / denominator - 1.0
 
 
def period_month_days(period: str) -> int:
    year, month = [int(value) for value in period.split("-")]
    return calendar.monthrange(year, month)[1]
 
 
def expected_segments(period: str) -> List[Tuple[date, date]]:
    year, month = [int(value) for value in period.split("-")]
    last_day = period_month_days(period)
    result: List[Tuple[date, date]] = []
    for start_day in range(1, last_day + 1, 3):
        end_day = min(start_day + 2, last_day)
        result.append((date(year, month, start_day), date(year, month, end_day)))
    return result
 
 
def missing_segments(paths: Sequence[Path], period: str) -> List[str]:
    actual = {parse_segment_dates(path, period) for path in paths}
    return [
        "%d\u65e5-%d\u65e5" % (start.day, end.day)
        for start, end in expected_segments(period)
        if (start, end) not in actual
    ]
 
 
def inspect_vehicle(spec: VehicleSpec, source_root: Path, work_root: Path, period: str) -> Dict[str, Any]:
    profile = next(profile for profile in PROFILES if profile.key == spec.profile_key)
    ledger_rows, ledger_source = parse_ledger(profile, source_root)
    selected_ledger = [row for row in ledger_rows if row.plate == spec.plate]
    if not selected_ledger:
        raise RuntimeError("No ledger rows for %s / %s" % (profile.enterprise, spec.plate))
    ledger_vehicles, ledger_total = aggregate_ledger(selected_ledger)
    ledger_vehicle = ledger_vehicles[spec.plate]
 
    track_rows, track_source = parse_track_summary(profile, source_root)
    track_vehicles = aggregate_tracks(track_rows)
    selected_track = track_vehicles.get(spec.plate)
    if not selected_track:
        raise RuntimeError("No monthly track summary for %s" % spec.plate)
 
    points, file_audits = load_track_points(spec, work_root, period)
    unique_points = deduplicate_points(points)
    distance_stats = point_distance_stats(unique_points)
    location_counties = Counter(
        "%s|%s|%s" % (point.province, point.prefecture, point.county)
        for point in unique_points
        if point.county
    )
    location_prefectures = Counter(point.prefecture for point in unique_points if point.prefecture)
    location_provinces = Counter(point.province for point in unique_points if point.province)
    location_days: Dict[str, set] = defaultdict(set)
    for point in unique_points:
        location_days["%s|%s|%s" % (
            point.province, point.prefecture, point.county
        )].add(point.timestamp.date())
    endpoint_evidence = endpoint_stats(unique_points, spec.endpoints)
    files = sorted((work_root / spec.directory).glob("*%s*.xls" % spec.plate[1:]))
    observed_dates = sorted({point.timestamp.date() for point in unique_points})
    year, month = [int(value) for value in period.split("-")]
    expected_dates = {date(year, month, day) for day in range(1, period_month_days(period) + 1)}
    missing_days = sorted(expected_dates - set(observed_dates))
 
    raw_vs_platform_rate = safe_rate(distance_stats["raw_distance"], selected_track["total_mileage"])
    clean_vs_platform_rate = safe_rate(distance_stats["clean_distance"], selected_track["total_mileage"])
    platform_vs_ledger_rate = safe_rate(selected_track["total_mileage"], ledger_vehicle["mileage"])
    ledger_vs_platform_rate = safe_rate(ledger_vehicle["mileage"], selected_track["total_mileage"])
    point_vs_ledger_rate = safe_rate(distance_stats["raw_distance"], ledger_vehicle["mileage"])
    average_trip_mileage = (
        ledger_vehicle["mileage"] / ledger_vehicle["trips"]
        if ledger_vehicle["trips"] > 0 else None
    )
    point_supported_trips = (
        distance_stats["raw_distance"] / average_trip_mileage
        if average_trip_mileage and average_trip_mileage > 0 else None
    )
    platform_supported_trips = (
        selected_track["total_mileage"] / average_trip_mileage
        if average_trip_mileage and average_trip_mileage > 0 else None
    )
 
    return {
        "city": profile.city,
        "enterprise": profile.enterprise,
        "profile_key": profile.key,
        "plate": spec.plate,
        "directory": str(work_root / spec.directory),
        "ledger": {
            "source_file": ledger_source.path,
            "routes": [row.route for row in selected_ledger if row.route],
            "route_groups": route_group_stats(selected_ledger),
            "trips": ledger_vehicle["trips"],
            "mileage": ledger_vehicle["mileage"],
            "freight": ledger_vehicle["freight"],
            "turnover": ledger_vehicle["turnover"],
        },
        "platform": {
            "source_file": track_source.path,
            "total_mileage": selected_track["total_mileage"],
            "complete_mileage": selected_track["complete_mileage"],
            "abnormal_mileage": selected_track["abnormal_mileage"],
            "anomaly_rate": selected_track["anomaly_rate"],
            "days": len(selected_track["days"]),
        },
        "points": {
            "file_count": len(files),
            "missing_segments": missing_segments(files, period),
            "valid_point_count": len(points),
            "unique_point_count": len(unique_points),
            "duplicate_point_count": len(points) - len(unique_points),
            "first_time": unique_points[0].timestamp if unique_points else None,
            "last_time": unique_points[-1].timestamp if unique_points else None,
            "day_count": len({point.timestamp.date() for point in unique_points}),
            "observed_dates": [str(value) for value in observed_dates],
            "missing_days": [str(value) for value in missing_days],
            "moving_day_count": len(distance_stats["moving_days"]),
            "clean_distance": distance_stats["clean_distance"],
            "raw_distance": distance_stats["raw_distance"],
            "rejected_time_gap": distance_stats["rejected_time_gap"],
            "rejected_speed": distance_stats["rejected_speed"],
            "top_provinces": top_counter(location_provinces),
            "top_prefectures": top_counter(location_prefectures),
            "top_counties": [
                (
                    name,
                    count,
                    len(location_days[name]),
                )
                for name, count in location_counties.most_common(10)
            ],
            "endpoints": endpoint_evidence,
            "unresolved_route_terms": list(spec.unresolved_route_terms),
        },
        "comparison": {
            "raw_vs_platform_rate": raw_vs_platform_rate,
            "clean_vs_platform_rate": clean_vs_platform_rate,
            "platform_vs_ledger_rate": platform_vs_ledger_rate,
            "ledger_vs_platform_rate": ledger_vs_platform_rate,
            "point_vs_ledger_rate": point_vs_ledger_rate,
            "average_trip_mileage": average_trip_mileage,
            "point_supported_trips": point_supported_trips,
            "platform_supported_trips": platform_supported_trips,
            "trip_support_rate": (
                platform_supported_trips / ledger_vehicle["trips"]
                if platform_supported_trips is not None and ledger_vehicle["trips"] > 0 else None
            ),
        },
        "files": [audit.to_dict() for audit in file_audits],
    }
 
 
def json_default(value: Any) -> Any:
    if isinstance(value, datetime):
        return value.isoformat(sep=" ")
    if isinstance(value, set):
        return sorted(value)
    raise TypeError("Unsupported value: %r" % (value,))
 
 
def main(argv: Optional[Sequence[str]] = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--period", default="2026-09")
    parser.add_argument("--source-root", required=True)
    parser.add_argument("--work-root", required=True)
    parser.add_argument("--output-json", required=True)
    args = parser.parse_args(argv)
 
    source_root = Path(args.source_root)
    work_root = Path(args.work_root)
    result = {
        "source_root": str(source_root),
        "work_root": str(work_root),
        "vehicles": [
            inspect_vehicle(spec, source_root, work_root, args.period)
            for spec in SELECTED_VEHICLES
        ],
    }
    with Path(args.output_json).open("w", encoding="utf-8") as handle:
        json.dump(result, handle, ensure_ascii=False, indent=2, default=json_default)
    return 0
 
 
if __name__ == "__main__":
    raise SystemExit(main())