
import os
import sys
import shutil
import subprocess
import site
from pathlib import Path

def setup_environment():
    """
    Rithmic Bridge Publisherを起動するための環境設定を行う。
    pythonnetに必要なDLLの配置や環境変数の設定を行う。
    """
    print("===================================================")
    print("  Rithmic Bridge Launcher (Python)")
    print("===================================================")

    # 1. 自身のPython DLL (python311.dll等) を特定
    base_prefix = Path(sys.base_prefix)
    major = sys.version_info.major
    minor = sys.version_info.minor
    dll_name = f"python{major}{minor}.dll"
    
    # 候補パス
    dll_candidates = [
        base_prefix / dll_name,
        base_prefix.parent / dll_name,
        # venv環境下の場合の考慮
        Path(sys.executable).parent / dll_name,
    ]
    
    python_dll = None
    for cand in dll_candidates:
        if cand.exists():
            python_dll = cand
            break
            
    if not python_dll:
        print(f"[ERROR] Could not find {dll_name} in typical locations.")
        print(f"  Base Prefix: {base_prefix}")
        sys.exit(1)
        
    print(f"[INFO] Found Python DLL: {python_dll}")

    # 2. pythonnetのインストール場所を特定
    # pythonnetパッケージの中から runtime/Python.Runtime.dll を探す
    runtime_dll = None
    try:
        # site-packagesから探す
        site_packages = site.getsitepackages()
        for sp in site_packages:
            p = Path(sp) / "pythonnet" / "runtime" / "Python.Runtime.dll"
            if p.exists():
                runtime_dll = p
                break
    except Exception as e:
        print(f"[WARNING] Failed to find pythonnet via site packages: {e}")

    # 見つからない場合はインポートして探す試み（ImportErrorになるかもしれないがパスは取れるかも）
    if not runtime_dll:
        try:
            import pythonnet
            runtime_dll = Path(os.path.dirname(pythonnet.__file__)) / "runtime" / "Python.Runtime.dll"
        except Exception:
            pass

    if runtime_dll and runtime_dll.exists():
        print(f"[INFO] Found Python.Runtime.dll at: {runtime_dll}")
        runtime_dir = runtime_dll.parent
        
        # 3. Python DLLをPython.Runtime.dllと同じ場所にコピー
        target_path = runtime_dir / dll_name
        try:
            if not target_path.exists() or target_path.stat().st_size != python_dll.stat().st_size:
                print(f"[INFO] Copying {python_dll} to {runtime_dir}...")
                shutil.copy2(python_dll, target_path)
            else:
                print("[INFO] Python DLL already exists in runtime directory.")
                
            # コピー先のDLLをPYTHONNET_PYDLLに設定
            os.environ["PYTHONNET_PYDLL"] = str(target_path)
            print(f"[INFO] Set PYTHONNET_PYDLL environment variable: {target_path}")

            # DLLのブロック解除 (Zone.Identifierの削除)
            try:
                print("[INFO] Unblocking DLLs...")
                subprocess.run(["powershell", "-Command", f"Unblock-File -Path '{runtime_dll}'"], check=False)
                subprocess.run(["powershell", "-Command", f"Unblock-File -Path '{target_path}'"], check=False)
            except Exception as e:
                print(f"[WARNING] Failed to unblock DLLs: {e}")
            
        except Exception as e:
            print(f"[WARNING] Failed to copy DLL: {e}")
            # コピー失敗時は元のパスを設定
            os.environ["PYTHONNET_PYDLL"] = str(python_dll)
    else:
        print("[WARNING] Could not find Python.Runtime.dll. Setting PYTHONNET_PYDLL to the original DLL path.")
        os.environ["PYTHONNET_PYDLL"] = str(python_dll)

    # 4. PATHにPythonのディレクトリを追加
    python_dir = str(python_dll.parent)
    scripts_dir = str(python_dll.parent / "Scripts")
    current_path = os.environ.get("PATH", "")
    os.environ["PATH"] = f"{python_dir};{scripts_dir};{current_path}"
    print(f"[INFO] Added to PATH: {python_dir}")

    # 5. メインプロセスの起動
    # PYTHONPATHを設定（srcディレクトリ）
    project_root = Path(__file__).parent.parent
    src_dir = project_root / "src"
    os.environ["PYTHONPATH"] = str(src_dir)
    
    print("-" * 50)
    
    # 実行対象のモジュール/スクリプトを決定
    # 引数がなければデフォルトのパブリッシャー
    target_args = sys.argv[1:]
    if not target_args:
        print("Starting Publisher (Default)...")
        cmd = [sys.executable, "-m", "rithmic_bridge.publisher", "--mode", "rapi"]
    else:
        # 引数が渡された場合はそれを実行
        # 例: tools/inspect_rapi.py を実行したい場合
        # python tools/launcher.py tools/inspect_rapi.py
        print(f"Starting Custom Command: {target_args}")
        cmd = [sys.executable] + target_args
    
    try:
        subprocess.run(cmd, check=True)
    except subprocess.CalledProcessError as e:
        print(f"[ERROR] Publisher exited with code {e.returncode}")
        sys.exit(e.returncode)
    except KeyboardInterrupt:
        print("\nStopping...")

if __name__ == "__main__":
    setup_environment()
