#!/usr/bin/env python3 """Run a bounded local Italy Query monitor with no booking side effects.""" from __future__ import annotations import argparse import os import random import sys import time from pathlib import Path from typing import Callable, Mapping REPO_ROOT = Path(__file__).resolve().parents[1] if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) from plugins.ita_plugin import ItaPlugin from tools.debug_ita_query import ( _get_query_credentials, _is_nonempty_query_result, _is_weak_entry_signal, _popup_text_for_log, _prepare_query_profile, _print_booking_form_structure, _print_failure_context, build_query_config, resolve_debug_route, ) from tools.debug_ita_session import ( DebugConfigurationError, resolve_chrome_path, ) from tools.ita_local_handoff import ( ITA_LOCAL_SIGNAL_TTL_SECONDS, publish_local_weak_signal, ) from vs_types import BizLogicError MIN_SAFE_WAIT_SECONDS = 60 DEFAULT_MAX_WAIT_SECONDS = 300 DEFAULT_MAX_PROBES = 10 MAX_ALLOWED_PROBES = 100 class _MonitorCancelled(Exception): """Internal control flow for a clean Ctrl+C.""" def _validate_monitor_limits( *, min_wait: int, max_wait: int, max_probes: int, ) -> None: if min_wait < MIN_SAFE_WAIT_SECONDS: raise DebugConfigurationError( f"min_wait must be at least {MIN_SAFE_WAIT_SECONDS} seconds" ) if max_wait < min_wait: raise DebugConfigurationError("max_wait must be greater than min_wait") if not 1 <= max_probes <= MAX_ALLOWED_PROBES: raise DebugConfigurationError( f"max_probes must be between 1 and {MAX_ALLOWED_PROBES}" ) def run_monitor( env: Mapping[str, str], *, apply: bool, non_interactive: bool, min_wait: int, max_wait: int, max_probes: int, publish_local_signal: bool = False, signal_publisher: Callable[[], object] | None = None, randint: Callable[[int, int], int] = random.randint, sleep: Callable[[float], None] = time.sleep, ) -> int: route = resolve_debug_route(env) route_log = ( f"service_id={route.service_id} routing_key={route.routing_key}" ) _validate_monitor_limits( min_wait=min_wait, max_wait=max_wait, max_probes=max_probes, ) if not apply: print( "ITA_MONITOR_PREFLIGHT_OK " f"{route_log} min_wait={min_wait} " f"max_wait={max_wait} max_probes={max_probes} " f"local_handoff={str(publish_local_signal).lower()} " "external_request=false" ) return 0 chrome_path = resolve_chrome_path(env) os.environ["CHROME_BIN"] = str(chrome_path) username, password = _get_query_credentials( env, non_interactive=non_interactive, ) profile_path = _prepare_query_profile(username) config = build_query_config( env, username=username, password=password, persistent_profile_path=profile_path, route=route, ) plugin = ItaPlugin(group_id="ita-monitor-local-debug") plugin.set_log(lambda message: print(message, flush=True)) plugin.set_config(config) exit_code = 0 cleanup_error: Exception | None = None try: plugin.create_session() print( "ITA_MONITOR_STARTED " f"{route_log} session_attempts=1 " f"max_probes={max_probes}" ) for probe_number in range(1, max_probes + 1): print( "ITA_MONITOR_PROBE_START " f"{route_log} probe={probe_number}" ) result = plugin.query(route.appointment_type()) if _is_weak_entry_signal(result): if publish_local_signal: publisher = signal_publisher or ( lambda: publish_local_weak_signal( service_id=route.service_id, routing_key=route.routing_key, ) ) publisher() print( "ITA_MONITOR_HANDOFF_PUBLISHED " f"{route_log} " f"ttl_seconds={ITA_LOCAL_SIGNAL_TTL_SECONDS} " "payload=metadata-only", flush=True, ) _print_booking_form_structure(plugin, route=route) print( "\aITA_MONITOR_WEAK_SIGNAL " f"{route_log} probe={probe_number} " "evidence=booking-form action=start-user-book-recheck-now", flush=True, ) exit_code = 4 break if _is_nonempty_query_result(result): print( "ITA_MONITOR_SAFE_STOP " f"{route_log} probe={probe_number} " "reason=non-empty-availability-result" ) exit_code = 4 break print( "ITA_MONITOR_NONE_AVAILABLE " f"{route_log} probe={probe_number}" ) if probe_number == max_probes: print( "ITA_MONITOR_MAX_PROBES_REACHED " f"{route_log} probes={max_probes}" ) break wait_seconds = randint(min_wait, max_wait) print( "ITA_MONITOR_WAIT " f"next_probe={probe_number + 1} seconds={wait_seconds}", flush=True, ) try: sleep(wait_seconds) except KeyboardInterrupt: raise _MonitorCancelled from None except _MonitorCancelled: print( "\nITA_MONITOR_CANCELLED " f"{route_log}", ) exit_code = 130 except KeyboardInterrupt: print( "\nITA_MONITOR_CANCELLED " f"{route_log}", ) exit_code = 130 except BizLogicError as exc: print( f"ITA_MONITOR_FAILED type={type(exc).__name__} " f"message={_popup_text_for_log(exc)}" ) _print_failure_context(plugin) exit_code = 1 except Exception as exc: print( f"ITA_MONITOR_FAILED type={type(exc).__name__} " f"message={_popup_text_for_log(exc)}" ) _print_failure_context(plugin) exit_code = 1 finally: try: plugin.cleanup() print("ITA_MONITOR_CLEANUP_OK") except Exception as exc: cleanup_error = exc print( f"ITA_MONITOR_CLEANUP_FAILED type={type(exc).__name__} " f"message={_popup_text_for_log(exc)}", file=sys.stderr, ) return 3 if cleanup_error is not None else exit_code def parse_args(argv: list[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser( description=( "Bounded route-configured Italy Query monitor. Without --run, " "performs a zero-network preflight only." ) ) parser.add_argument( "--run", action="store_true", help="Start the bounded real website monitor.", ) parser.add_argument( "--non-interactive", action="store_true", help="Fail instead of prompting when local credentials are unavailable.", ) parser.add_argument( "--min-wait", type=int, default=MIN_SAFE_WAIT_SECONDS, help=f"Minimum seconds between probes (floor: {MIN_SAFE_WAIT_SECONDS}).", ) parser.add_argument( "--max-wait", type=int, default=DEFAULT_MAX_WAIT_SECONDS, help="Maximum seconds between probes.", ) parser.add_argument( "--max-probes", type=int, default=DEFAULT_MAX_PROBES, help=f"Maximum probes in one run (ceiling: {MAX_ALLOWED_PROBES}).", ) parser.add_argument( "--publish-local-signal", action="store_true", help=( "On a verified weak signal, atomically notify one local Book " "debugger. Production signaling behavior is unchanged." ), ) return parser.parse_args(argv) def main(argv: list[str] | None = None) -> int: args = parse_args(argv) try: return run_monitor( os.environ, apply=args.run, non_interactive=args.non_interactive, min_wait=args.min_wait, max_wait=args.max_wait, max_probes=args.max_probes, publish_local_signal=args.publish_local_signal, ) except DebugConfigurationError as exc: print(f"ITA_MONITOR_CONFIG_ERROR: {exc}", file=sys.stderr) return 2 if __name__ == "__main__": raise SystemExit(main())