#!/usr/bin/env python3 """Run one Italy Book recheck; by default stop before AVANTI. This discovery tool logs in with the eventual user's account, calls ``ItaPlugin.book()`` exactly once with a weak Query trigger, and cleans up. The current Book implementation rechecks the explicitly configured route and reads allowlisted form structure. It never fills or submits the form, opens the Calendar, sends OTP, or confirms an appointment in default discovery mode. Explicit --production-workflow exercises applicant login/OTP/selection through the public Book entry. Final submission remains disabled in both modes. Optional --verify-receipts reuses the existing receipt-baseline gate after selection; it never enables final submission or consumes a final-attempt fence. """ from __future__ import annotations import argparse import json import os 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 ( BOOKING_CALENDAR_PREFINAL_STOP_LABEL, BOOKING_FORM_DISCOVERY_STOP_LABEL, BOOKING_RECHECK_NONE_AVAILABLE_LABEL, ItaPlugin, ) from tools.debug_ita_query import ( ItaDebugRoute, _print_booking_form_structure, _print_failure_context, build_query_config, resolve_debug_route, ) from tools.debug_ita_session import ( DebugConfigurationError, _get_credentials, _text_for_log, resolve_chrome_path, ) from tools.ita_local_handoff import ( ItaLocalSignalStaleError, claim_local_weak_signal, ) from utils.ita_local_profile import ITA_QUERY_ACCOUNT_FILE from utils.local_account import ( LocalAccountConfigurationError, load_local_account, ) from vs_types import AvailabilityStatus, BizLogicError, VSQueryResult class _BookArmCancelled(Exception): """Internal control flow for a clean Ctrl+C while waiting in armed mode.""" DEFAULT_LOCAL_SIGNAL_WAIT_SECONDS = 900 MAX_LOCAL_SIGNAL_WAIT_SECONDS = 900 LOCAL_SIGNAL_POLL_SECONDS = 0.1 def _assert_distinct_local_accounts(book_username: str) -> None: """Fail closed unless local Query and Book roles use different accounts.""" if not ITA_QUERY_ACCOUNT_FILE.exists(): raise DebugConfigurationError( "Automatic local handoff requires the private Italy Query account " "file so Query and Book accounts can be verified as different" ) try: query_account = load_local_account(ITA_QUERY_ACCOUNT_FILE) except LocalAccountConfigurationError as exc: raise DebugConfigurationError( "Local Italy Query account config is invalid" ) from exc if ( query_account.username.strip().casefold() == book_username.strip().casefold() ): raise DebugConfigurationError( "Automatic local handoff requires different Query and Book accounts" ) def _wait_for_local_signal( *, route: ItaDebugRoute, timeout_seconds: int, signal_claimer: Callable[[], object | None] | None, monotonic: Callable[[], float], sleep: Callable[[float], None], ) -> object | None: claimer = signal_claimer or ( lambda: claim_local_weak_signal( expected_service_id=route.service_id, expected_routing_key=route.routing_key, ) ) deadline = monotonic() + timeout_seconds while True: try: signal = claimer() except ItaLocalSignalStaleError: print( "ITA_BOOK_SIGNAL_IGNORED " f"routing_key={route.routing_key} " f"service_id={route.service_id} reason=stale", flush=True, ) signal = None if signal is not None: return signal remaining = deadline - monotonic() if remaining <= 0: return None try: sleep(min(LOCAL_SIGNAL_POLL_SECONDS, remaining)) except KeyboardInterrupt: raise _BookArmCancelled from None def run_book_recheck_once( env: Mapping[str, str], *, non_interactive: bool, arm: bool = False, wait_for_local_signal: bool = False, signal_timeout: int = DEFAULT_LOCAL_SIGNAL_WAIT_SECONDS, signal_claimer: Callable[[], object | None] | None = None, monotonic: Callable[[], float] = time.monotonic, sleep: Callable[[float], None] = time.sleep, production_workflow: bool = False, auto_otp: bool = False, verify_receipts: bool = False, ) -> int: if type(verify_receipts) is not bool or (verify_receipts and not production_workflow): raise DebugConfigurationError("--verify-receipts requires --production-workflow") if auto_otp and not production_workflow: raise DebugConfigurationError("--auto-otp requires --production-workflow") if production_workflow and (non_interactive or arm or wait_for_local_signal): raise DebugConfigurationError("--production-workflow requires interactive mode without legacy handoff flags") route = resolve_debug_route(env) route_log = ( f"service_id={route.service_id} routing_key={route.routing_key}" ) if arm and wait_for_local_signal: raise DebugConfigurationError( "--arm and --wait-for-local-signal are mutually exclusive" ) if ( wait_for_local_signal and not 1 <= signal_timeout <= MAX_LOCAL_SIGNAL_WAIT_SECONDS ): raise DebugConfigurationError( "signal_timeout must be between 1 and " f"{MAX_LOCAL_SIGNAL_WAIT_SECONDS} seconds" ) chrome_path = resolve_chrome_path(env) os.environ["CHROME_BIN"] = str(chrome_path) credential_env = env if production_workflow: # Match the existing Book gate: never silently borrow Query credentials. credential_env = {"ITA_USERNAME": env.get("ITA_BOOK_USERNAME", ""), "ITA_PASSWORD": env.get("ITA_BOOK_PASSWORD", "")} print("ITA_BOOK_WORKFLOW_CREDENTIALS role=applicant profile=temporary source=book_environment_or_prompt", flush=True) username, password = _get_credentials(credential_env, non_interactive=non_interactive) if wait_for_local_signal: _assert_distinct_local_accounts(username) config_builder = build_query_config if production_workflow: from tools.debug_ita_calendar_gate import build_calendar_gate_config config_builder = build_calendar_gate_config config = config_builder( env, username=username, password=password, route=route, ) if production_workflow: config.free_config.update(query_mode="services_probe", otp_mode="manual", final_submit_enabled=False) if auto_otp: from plugins.ita_plugin import validate_cloud_otp_environment from plugins.ita_plugin import ItaProtocolError, OtpMailConfig from plugins.ita_plugin import CalendarGateError try: mail = OtpMailConfig(env.get("ITA_OTP_AUTHORIZATION_EMAIL", "")) validate_cloud_otp_environment(mail, username) except (ItaProtocolError, CalendarGateError): raise DebugConfigurationError( "Automatic OTP requires ITA_OTP_AUTHORIZATION_EMAIL and INFO-or-higher SDK logging" ) from None config.free_config["apt_configs"][route.routing_key]["mail"] = { "authorization_email": mail.authorization_email, } config.free_config["otp_mode"] = "cloud" print("ITA_BOOK_WORKFLOW_OTP mode=cloud final_submit_enabled=false", flush=True) plugin = ItaPlugin(group_id="ita-book-local-debug") plugin.set_log(lambda message: print(message, flush=True)) plugin.set_config(config) trigger = VSQueryResult( success=True, apt_type=route.appointment_type(), availability_status=AvailabilityStatus.NoneAvailable, ) exit_code = 0 cleanup_error: Exception | None = None audit = None try: plugin.create_session() if production_workflow: from plugins.ita_plugin import CalendarRequestAudit audit = CalendarRequestAudit(plugin.page, include_time_slots=True) audit.start() if arm: print( "ITA_BOOK_ARMED " f"{route_log} stage=user-area" ) try: input("Press Enter once the Query account reports a weak signal: ") except KeyboardInterrupt: raise _BookArmCancelled from None should_recheck = True if wait_for_local_signal: print( "ITA_BOOK_WAITING_FOR_LOCAL_SIGNAL " f"{route_log} " f"timeout_seconds={signal_timeout}", flush=True, ) signal = _wait_for_local_signal( route=route, timeout_seconds=signal_timeout, signal_claimer=signal_claimer, monotonic=monotonic, sleep=sleep, ) if signal is None: print( "ITA_BOOK_SIGNAL_WAIT_TIMEOUT " f"{route_log} book_attempts=0" ) exit_code = 5 should_recheck = False else: print( "ITA_BOOK_SIGNAL_CLAIMED " f"{route_log} " "evidence=booking-form", flush=True, ) if should_recheck: print( "ITA_BOOK_RECHECK_START " f"{route_log} book_attempt=1" ) result = plugin.book(trigger, user_inputs={"username": username} if production_workflow else {}) if production_workflow: from plugins.ita_plugin import read_calendar_service, verify_precommit_selection counts = audit.settled_snapshot() if counts["finalRequests"] != 0: raise BizLogicError("Book workflow observed an unexpected final request; do not rerun") selected = result.label == BOOKING_CALENDAR_PREFINAL_STOP_LABEL and result.success is False report = {"selectionVerified": False, "bookResultSuccess": result.success, "finalSubmissionEnabled": False, "requests": counts} if selected: approval = plugin.last_booking_precommit verify_precommit_selection(plugin.page, runtime_service=read_calendar_service(plugin.page), approval=approval) report.update(selectionVerified=True, selectedDate=approval.candidate.day.isoformat(), selectedTime=approval.candidate.time_label, remaining=approval.candidate.slots_free) if verify_receipts: # Reuse the existing gate, including its background-tab # request audit and selection-preservation check. from tools.debug_ita_book_gate import _verify_receipt_baseline baseline = _verify_receipt_baseline(plugin, plugin._resolve_route(trigger.apt_type)) if audit.settled_snapshot() != counts: raise BizLogicError("Receipt verification changed the Book request budget; do not rerun") report["receiptBaseline"] = baseline print("ITA_BOOK_WORKFLOW_RECEIPT_BASELINE=" + json.dumps(baseline, sort_keys=True), flush=True) elif result.success or result.label != BOOKING_RECHECK_NONE_AVAILABLE_LABEL: raise BizLogicError("Book workflow did not return the expected pre-final or no-availability result") exit_code = 0 if selected else 2 print("ITA_BOOK_WORKFLOW_RESULT=" + json.dumps(report, sort_keys=True), flush=True) elif result.success: print( "ITA_BOOK_SAFE_STOP " f"{route_log} " "reason=unexpected-success-before-avanti" ) exit_code = 4 elif result.label == BOOKING_FORM_DISCOVERY_STOP_LABEL: _print_booking_form_structure( plugin, raw_structure=plugin.last_booking_form_structure, route=route, ) print( "ITA_BOOK_DISCOVERY_STOP " f"{route_log} " "stage=before-avanti submit_attempts=0" ) exit_code = 4 elif result.label == BOOKING_RECHECK_NONE_AVAILABLE_LABEL: print( "ITA_BOOK_RECHECK_NONE_AVAILABLE " f"{route_log}" ) else: print( "ITA_BOOK_SAFE_STOP " f"{route_log} reason=unexpected-result" ) exit_code = 4 except _BookArmCancelled: label = ( "ITA_BOOK_SIGNAL_WAIT_CANCELLED" if wait_for_local_signal else "ITA_BOOK_ARM_CANCELLED" ) print( f"\n{label} {route_log} book_attempts=0" ) exit_code = 130 except BizLogicError as exc: print( f"ITA_BOOK_FAILED type={type(exc).__name__} " f"message={_text_for_log(exc)}" ) _print_failure_context(plugin) if plugin.last_booking_form_structure is not None: _print_booking_form_structure( plugin, raw_structure=plugin.last_booking_form_structure, route=route, ) exit_code = 1 except Exception as exc: print( f"ITA_BOOK_FAILED type={type(exc).__name__} " f"message={_text_for_log(exc)}" ) _print_failure_context(plugin) exit_code = 1 finally: if audit is not None: try: counts = audit.settled_snapshot() if counts["finalRequests"] != 0: exit_code = 1 print("ITA_BOOK_WORKFLOW_AUDIT=" + json.dumps(counts, sort_keys=True), flush=True) except Exception: exit_code = 1 print("ITA_BOOK_WORKFLOW_AUDIT_FAILED", flush=True) finally: try: audit.stop() except Exception: exit_code = 1 print("ITA_BOOK_WORKFLOW_AUDIT_CLEANUP_FAILED", flush=True) try: plugin.cleanup() print("ITA_BOOK_CLEANUP_OK") except Exception as exc: cleanup_error = exc print( f"ITA_BOOK_CLEANUP_FAILED type={type(exc).__name__} " f"message={_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=( "One-shot route-configured Italy Book recheck debugger " "(default: stop before AVANTI; production-workflow: stop after selection; never confirm)." ) ) parser.add_argument( "--non-interactive", action="store_true", help="Fail instead of prompting when credentials are missing.", ) parser.add_argument( "--production-workflow", action="store_true", help="Exercise the public Book entry through manual OTP and Calendar selection; never submit final.", ) parser.add_argument( "--auto-otp", action="store_true", help="Use the existing cloud mail API in production-workflow instead of prompting for OTP; never confirm.", ) parser.add_argument( "--verify-receipts", action="store_true", help="With production-workflow, verify the existing receipt baseline without submitting a booking.", ) wait_group = parser.add_mutually_exclusive_group() wait_group.add_argument( "--arm", action="store_true", help=( "Log in and wait at /UserArea until Enter is pressed, then perform " "the one safe Book recheck." ), ) wait_group.add_argument( "--wait-for-local-signal", action="store_true", help=( "Log in with the user account, atomically wait for one local Query " "weak signal, then perform one independent safe recheck." ), ) parser.add_argument( "--signal-timeout", type=int, default=DEFAULT_LOCAL_SIGNAL_WAIT_SECONDS, help=( "Maximum seconds to keep the user Session armed while waiting " f"(ceiling: {MAX_LOCAL_SIGNAL_WAIT_SECONDS})." ), ) return parser.parse_args(argv) def main(argv: list[str] | None = None) -> int: args = parse_args(argv) try: if args.auto_otp and not args.production_workflow: raise DebugConfigurationError("--auto-otp requires --production-workflow") if args.verify_receipts and not args.production_workflow: raise DebugConfigurationError("--verify-receipts requires --production-workflow") if args.production_workflow: extra = {"auto_otp": True} if args.auto_otp else {} if args.verify_receipts: extra["verify_receipts"] = True return run_book_recheck_once( os.environ, non_interactive=args.non_interactive, arm=args.arm, wait_for_local_signal=args.wait_for_local_signal, signal_timeout=args.signal_timeout, production_workflow=True, **extra, ) return run_book_recheck_once( os.environ, non_interactive=args.non_interactive, arm=args.arm, wait_for_local_signal=args.wait_for_local_signal, signal_timeout=args.signal_timeout, ) except DebugConfigurationError as exc: print(f"ITA_BOOK_CONFIG_ERROR: {exc}", file=sys.stderr) return 2 if __name__ == "__main__": raise SystemExit(main())