
import sys
import os
import time
import clr
import System
from System.IO import File

# Windows Python Environment Check
print(f"Python Version: {sys.version}")

# Add libs path
current_dir = os.getcwd()
libs_dir = os.environ.get("RAPI_DLL_DIR", "C:\\temp\\RithmicBridgeTemp")

if not os.path.exists(libs_dir):
    # Fallback to relative path
    libs_dir = os.path.join(current_dir, "libs")

print(f"Libs Dir: {libs_dir}")
sys.path.append(libs_dir)
os.environ['PATH'] = libs_dir + os.pathsep + os.environ['PATH']

try:
    # Load DLL
    dll_path = os.path.join(libs_dir, "rapiplus.dll")
    System.Reflection.Assembly.LoadFrom(dll_path)
    clr.AddReference("rapiplus")
    import com.omnesys.rapi as rapi
    print("RAPI+ DLL Loaded Successfully.")
except Exception as e:
    print(f"DLL Load Failed: {e}")
    sys.exit(1)

# Compile Wrapper
from System.CodeDom.Compiler import CodeDomProvider, CompilerParameters

CS_SOURCE = """
using System;
using com.omnesys.rapi;

namespace RithmicWrapper {
    public class AdmCallbacks : com.omnesys.rapi.AdmCallbacks {
        public override void Alert(AlertInfo oInfo) {
            Console.WriteLine("[Plugin] AdmAlert received");
        }
    }

    public class RCallbacks : com.omnesys.rapi.RCallbacks {
        public override void Alert(AlertInfo oInfo) {
            Console.WriteLine("[Plugin] RAlert received");
        }
        public override void LineUpdate(LineInfo oInfo) {
            Console.WriteLine("[Plugin] LineUpdate received");
        }
    }
}
"""

def compile_wrapper():
    provider = CodeDomProvider.CreateProvider("CSharp")
    params = CompilerParameters()
    params.GenerateInMemory = True
    params.ReferencedAssemblies.Add("System.dll")
    params.ReferencedAssemblies.Add(os.path.join(libs_dir, "rapiplus.dll"))
    results = provider.CompileAssemblyFromSource(params, CS_SOURCE)
    
    if results.Errors.HasErrors:
        print("Wrapper Compilation Failed.")
        return None
    return results.CompiledAssembly

wrapper_asm = compile_wrapper()
if not wrapper_asm:
    sys.exit(1)

AdmCallbacksType = wrapper_asm.GetType("RithmicWrapper.AdmCallbacks")
RCallbacksType = wrapper_asm.GetType("RithmicWrapper.RCallbacks")

# Test Ports
PORTS = [3010, 3011, 3012, 3013]
HOST = "127.0.0.1"
ENV_KEY = "rithmic_paper_domain"
USER = os.environ.get("RITHMIC_USER", "dummy")
PWD = os.environ.get("RITHMIC_PASSWORD", "dummy")

def test_port(port):
    addr = f"{HOST}:{port}"
    print(f"\n--- Testing Plug-in Port: {addr} ---")
    
    params = rapi.REngineParams()
    params.AppName = "TestLocalPlugin"
    params.AppVersion = "1.0.0"
    params.LogFilePath = os.path.abspath(f"test_plugin_{port}.log")
    
    try:
        params.AdmCallbacks = System.Activator.CreateInstance(AdmCallbacksType)
    except Exception as e:
        print(f"Callback Init Error: {e}")
        return False

    params.DmnSrvrAddr = addr
    params.DomainName = ENV_KEY
    params.LicSrvrAddr = addr
    params.LocBrokAddr = addr
    params.LoggerAddr = addr
    
    engine = None
    try:
        engine = rapi.REngine(params)
        print("REngine Initialized.")
        
        callbacks = System.Activator.CreateInstance(RCallbacksType)
        cnnct_pt = addr
        
        print("Sending Login...")
        engine.login(
            callbacks,
            ENV_KEY, USER, PWD, cnnct_pt,
            ENV_KEY, USER, PWD, cnnct_pt,
            cnnct_pt,
            ENV_KEY, USER, PWD, cnnct_pt
        )
        print("Login sent. Waiting 5s...")
        time.sleep(5)
        
        print("Done.")
        return True

    except Exception as e:
        print(f"Connection Failed: {e}")
        return False
    finally:
        if engine:
            try:
                engine.shutdown()
            except:
                pass

if __name__ == "__main__":
    from dotenv import load_dotenv
    load_dotenv()
    
    for port in PORTS:
        test_port(port)
