#!/usr/bin/env python3
"""Validate the tt_response Python runtime without opening service connections."""

from __future__ import annotations

import argparse
import importlib
import os
from pathlib import Path
import sys


REQUIRED_MODULES = (
    "Crypto",
    "backend.settings",
    "confluent_kafka",
    "django",
    "psycopg2",
    "redis",
    "requests",
    "rest_framework",
)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--app-dir", required=True)
    parser.add_argument("--virtual-env", required=True)
    options = parser.parse_args()

    app_dir = Path(options.app_dir)
    virtual_env = Path(options.virtual_env)
    if not app_dir.is_absolute() or not virtual_env.is_absolute():
        raise SystemExit("tt_response runtime paths must be absolute")
    if app_dir.resolve() not in Path(__file__).resolve().parents:
        raise SystemExit("tt_response preflight must run from the deployed checkout")
    if Path(sys.prefix).resolve() != virtual_env.resolve():
        raise SystemExit("tt_response preflight is not running inside the selected virtualenv")

    worker = app_dir / "kafka_consumer" / "tt_response.py"
    if not worker.is_file():
        raise SystemExit("tt_response worker script is absent")
    compile(worker.read_bytes(), str(worker), "exec")

    original_path = list(sys.path)
    try:
        sys.path.insert(0, str(app_dir))
        for module_name in REQUIRED_MODULES:
            importlib.import_module(module_name)
    finally:
        sys.path[:] = original_path

    print("tt_response virtualenv preflight passed")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
