#!/usr/bin/env python3
"""
Benchmark-Skript für cli-anything-zotero über SSH auf Windows.
Voraussetzung: zotero-cli ist auf Windows installiert und Zotero inkl. JS Bridge läuft.
"""
import json
import subprocess
import time
from pathlib import Path

WINDOWS_HOST = "ml@192.168.0.28"
SSH_KEY = "/home/ml/.ssh/id_ed25519_zotero"
ZOTERO_CLI = r"C:\Users\ml\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\Scripts\zotero-cli.exe"
TEST_ITEM = "F5724CQV"
TEST_COLLECTION = "V6ERXWDL"
RESULTS_FILE = Path(__file__).with_suffix(".json")


def run_ssh(cmd: str, timeout: int = 60) -> tuple[str, float, int]:
    """Führt einen Befehl über SSH auf Windows aus."""
    full_cmd = f'"{ZOTERO_CLI}" {cmd}'
    start = time.perf_counter()
    proc = subprocess.run(
        ["ssh", "-i", SSH_KEY, WINDOWS_HOST, full_cmd],
        capture_output=True,
        text=True,
        encoding="utf-8",
        errors="replace",
        timeout=timeout,
    )
    elapsed = time.perf_counter() - start
    return proc.stdout + proc.stderr, elapsed, proc.returncode


def main():
    results = []

    tests = [
        ("app ping", "--json app ping", 30),
        ("app plugin-status", "--json app plugin-status", 30),
        ("item get", f"--json item get {TEST_ITEM}", 30),
        ("item children", f"--json item children {TEST_ITEM}", 30),
        ("item notes", f"--json item notes {TEST_ITEM}", 30),
        ("item search-fulltext", '--json item search-fulltext "trauma"', 60),
        ("item annotations", f"--json item annotations {TEST_ITEM}", 30),
        ("collection list", "--json collection list", 30),
        ("collection items", f"--json collection items {TEST_COLLECTION}", 60),
        ("item context", f"--json item context {TEST_ITEM}", 30),
        ("item citation", f"--json item citation {TEST_ITEM}", 30),
        ("item search-annotations", '--json item search-annotations "method"', 60),
    ]

    for name, cmd, timeout in tests:
        print(f"Running: {name} ...")
        output, elapsed, rc = run_ssh(cmd, timeout)
        result = {
            "tool": "cli-anything-zotero",
            "test": name,
            "command": cmd,
            "elapsed_seconds": round(elapsed, 3),
            "return_code": rc,
            "output_preview": output[:500],
        }
        results.append(result)
        print(f"  -> {elapsed:.3f}s rc={rc}")

    RESULTS_FILE.write_text(json.dumps(results, indent=2, ensure_ascii=False), encoding="utf-8")
    print(f"\nErgebnisse geschrieben nach: {RESULTS_FILE}")


if __name__ == "__main__":
    main()
