"""
R|API+ DLL調査ツール

Windows環境で実行し、R|Trader ProのプラグインDLLを解析する。
DLL内のクラスやメソッドを列挙し、API仕様の手がかりを得る。
"""

import os
import sys
from pathlib import Path

# プロジェクトルートの設定
PROJECT_ROOT = Path(__file__).parent.parent
sys.path.append(str(PROJECT_ROOT))

# .env読み込み
try:
    from dotenv import load_dotenv
    load_dotenv(PROJECT_ROOT / ".env")
except ImportError:
    print("Warning: python-dotenv not installed.")


def inspect_dll():
    print("=== R|API+ DLL Inspector ===")
    
    # pythonnetのチェック
    try:
        import clr
        print("[OK] pythonnet is available.")
    except ImportError:
        print("[ERROR] pythonnet is not installed.")
        print("Run: pip install pythonnet")
        return

    # DLLディレクトリの特定
    dll_dir = os.environ.get("RAPI_DLL_DIR")
    if not dll_dir:
        # 一般的なパスを試行
        candidates = [
            r"C:\Program Files (x86)\Rithmic\Rithmic Trader Pro",
            r"C:\Program Files\Rithmic\Rithmic Trader Pro",
        ]
        for path in candidates:
            if os.path.exists(path):
                dll_dir = path
                print(f"[INFO] Found DLL directory: {dll_dir}")
                break
    
    if not dll_dir or not os.path.isdir(dll_dir):
        print(f"[ERROR] DLL directory not found based on RAPI_DLL_DIR or common paths.")
        print(f"Current value: {dll_dir}")
        return

    sys.path.append(dll_dir)

    # 調査対象DLL
    target_dlls = [
        "RithmicPlugin",
        "OmneChannel",
        "OmneStreamEngine",
        "OmneVerse",
        "RApi",  # もしかしたら
    ]

    for dll_name in target_dlls:
        dll_path = os.path.join(dll_dir, f"{dll_name}.dll")
        if not os.path.exists(dll_path):
            continue

        print(f"\n--- Loading DLL: {dll_name} ---")
        try:
            clr.AddReference(dll_path)
            print(f"[SUCCESS] Loaded {dll_name}")
            
            # アセンブリとしてロードして型情報を取得
            try:
                import System
                assembly = System.Reflection.Assembly.LoadFrom(dll_path)
                types = assembly.GetTypes()
                
                print(f"Found {len(types)} types.")
                
                # 特に関連しそうな型を探す
                interesting_types = []
                for t in types:
                    name = t.FullName
                    if "RApi" in name or "Plugin" in name or "Callback" in name or "Rithmic" in name:
                        interesting_types.append(t)
                
                print(f"Interesting types ({len(interesting_types)}):")
                for t in interesting_types:
                    print(f"  - {t.FullName}")
                    # メソッドも少し表示
                    methods = t.GetMethods()
                    for m in methods[:5]: # 全部出すと多いので
                        print(f"      Method: {m.Name}")
                        
            except Exception as e:
                print(f"  [Error inspecting types] {e}")

        except Exception as e:
            print(f"[ERROR] Failed to load {dll_name}: {e}")

if __name__ == "__main__":
    inspect_dll()
