# -*- coding: utf-8 -*- """Deterministic plan/actual reconciliation for the local agenda.""" from __future__ import annotations from datetime import datetime from typing import Any import re try: from .agenda_contracts import agenda_entry_from_activity, agenda_entry_from_plan, normalize_observed_activity from .calendar_system import parse_datetime except ImportError: from agenda_contracts import agenda_entry_from_activity, agenda_entry_from_plan, normalize_observed_activity from calendar_system import parse_datetime PRIORITY = {"L0": 0, "L1": 1, "L2": 2, "L3": 3, "L4": 4, "L5": 5} def _normalized_text(value: Any) -> str: text = str(value or "").lower().strip() text = re.sub(r"[^0-9a-z\u4e00-\u9fff]+", "", text) return text def _tokens(value: Any) -> set[str]: text = _normalized_text(value) if not text: return set() tokens = {text} tokens.update(text[index:index + 2] for index in range(max(0, len(text) - 1))) tokens.update(text[index:index + 3] for index in range(max(0, len(text) - 2))) return {token for token in tokens if len(token) >= 2} def _interval(item: dict[str, Any], now: datetime) -> tuple[datetime | None, datetime | None]: try: start = parse_datetime(item.get("start_at"), default=now) except Exception: return None, None try: end = parse_datetime(item.get("end_at"), default=start) except Exception: end = start return start, end def _overlaps(plan: dict[str, Any], activity: dict[str, Any], now: datetime) -> bool: ps, pe = _interval(plan, now) a_s, a_e = _interval(activity, now) if not ps or not a_s: return False if pe <= ps: pe = ps if a_e <= a_s: a_e = a_s return ps < a_e and a_s < pe def _title_matches(plan: dict[str, Any], activity: dict[str, Any]) -> bool: plan_id = str(plan.get("plan_id") or plan.get("event_id") or "") refs = {str(item) for item in (activity.get("source_refs") or []) if str(item)} if plan_id and plan_id in refs: return True plan_text = _normalized_text(plan.get("title") or plan.get("activity")) activity_text = _normalized_text(activity.get("title")) if not plan_text or not activity_text: return False if plan_text in activity_text or activity_text in plan_text: return True plan_tokens = _tokens(plan_text) activity_tokens = _tokens(activity_text) shared = plan_tokens.intersection(activity_tokens) return bool(shared and (any(len(token) >= 3 for token in shared) or len(shared) >= 2)) def reconcile( plans: list[dict[str, Any]], activities: list[dict[str, Any]], *, now: datetime, ) -> dict[str, Any]: normalized_activities = [] for activity in activities: try: normalized_activities.append(normalize_observed_activity(activity, now=now)) except Exception: continue matched: dict[str, list[dict[str, Any]]] = {} used_activity_ids: set[str] = set() results = [] entries = [] for raw_plan in plans: plan = dict(raw_plan) plan_id = str(plan.get("plan_id") or plan.get("event_id") or "") overlaps = [activity for activity in normalized_activities if _overlaps(plan, activity, now)] matching = [activity for activity in overlaps if _title_matches(plan, activity)] selected = matching or overlaps if selected: matched[plan_id] = selected used_activity_ids.update(str(item.get("activity_id")) for item in selected) strongest = max((PRIORITY.get(str(item.get("evidence_level")), 0) for item in selected), default=0) if matching: status = "completed" if all(item.get("status") == "completed" for item in selected) else "active" reason = "实际活动与计划主题和时间匹配" elif strongest >= PRIORITY["L2"]: status = "overridden" reason = "实际活动覆盖原计划" else: status = "unknown" reason = "活动证据不足" plan["status"] = status plan["reconciliation_reason"] = reason plan["reconciled_activity_ids"] = [item.get("activity_id") for item in selected] entries.append(agenda_entry_from_plan(plan, reason=reason)) entries.extend(agenda_entry_from_activity(item, source_refs=[plan_id, item.get("activity_id")]) for item in selected) else: if plan.get("status") not in {"cancelled", "deferred"} and _plan_is_past(plan, now): plan["status"] = "unknown" plan["reconciliation_reason"] = "窗口结束但没有足够实际证据" entries.append(agenda_entry_from_plan(plan, reason=plan.get("reconciliation_reason", ""))) results.append(plan) for activity in normalized_activities: if str(activity.get("activity_id")) not in used_activity_ids: entries.append(agenda_entry_from_activity(activity)) entries.sort(key=lambda item: (0 if item.get("kind") == "observed_activity" else 1, str(item.get("start_at") or ""))) return {"plans": results, "activities": normalized_activities, "entries": entries, "matched": matched} def _plan_is_past(plan: dict[str, Any], now: datetime) -> bool: _, end = _interval(plan, now) return bool(end and end <= now)