#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TRX V300 launcher:
1) Load the merged TRX app as a module (without starting it).
2) Load TRX_MASTER_PATCH_V300 into the SAME process/module.
3) Start the merged app's own runner.

Place this file next to:
- TRX_FINAL_MERGED_AI_FIXED.py
- TRX_MASTER_PATCH_V300.py
"""

import importlib.util
import os
import sys
import traceback


HERE = os.path.dirname(os.path.abspath(__file__))
MAIN_PATH = os.path.join(HERE, "TRX_FINAL_MERGED_AI_FIXED.py")
PATCH_PATH = os.path.join(HERE, "TRX_MASTER_PATCH_V300.py")


def load_module(name: str, path: str):
    if not os.path.isfile(path):
        raise FileNotFoundError(path)

    spec = importlib.util.spec_from_file_location(name, path)
    if spec is None or spec.loader is None:
        raise RuntimeError(f"Cannot create module spec: {path}")

    mod = importlib.util.module_from_spec(spec)
    sys.modules[name] = mod
    spec.loader.exec_module(mod)
    return mod


def main():
    print("=" * 72)
    print(" TRX V300 SINGLE-PROCESS LAUNCHER")
    print("=" * 72)

    # The merged app is imported, not executed as __main__,
    # so its own final runner does not start yet.
    print(f"[RUNNER] Loading main: {MAIN_PATH}")
    trx = load_module("trx_app", MAIN_PATH)

    # Expose the exact same module name expected by the patch.
    sys.modules["trx"] = trx
    sys.modules["trxf2"] = trx
    sys.modules["trxf2_main"] = trx

    print(f"[RUNNER] Loading patch: {PATCH_PATH}")
    load_module("trx_master_patch_v300", PATCH_PATH)

    print("[RUNNER] V300 patch loaded into the SAME process.")
    print("[RUNNER] Starting merged TRX application...")

    run_fn = getattr(trx, "_trx290_run", None)
    if callable(run_fn):
        return run_fn()

    run_fn = getattr(trx, "_run", None)
    if callable(run_fn):
        return run_fn()

    main_fn = getattr(trx, "main", None)
    if callable(main_fn):
        import asyncio
        return asyncio.run(main_fn())

    raise RuntimeError("No supported TRX startup function was found.")


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n[RUNNER] Interrupted.")
    except SystemExit:
        raise
    except Exception as exc:
        print(f"\n[RUNNER][FATAL] {type(exc).__name__}: {exc}")
        traceback.print_exc(limit=40)
        raise
