"""Forward CLI to SSH when fiber_map says the target lives on another host."""

import json
import sys

from fiwi.patch_panel import effective_panel_slots
from fiwi import fiber_map_io as fm
from fiwi.fiber_radio_port import FiberRadioPort
from fiwi.ssh import SshNode, apply_fiwi_ssh_env


def dispatch_fiber_mapped_ssh_if_needed(argv):
    """
    If the fiber map says this port is on another host (ssh / host+user), forward over SSH
    without importing brainstem locally. Returns exit code, or None to continue normally.
    """
    apply_fiwi_ssh_env()
    try:
        doc = fm.load_fiber_map_document()
    except (OSError, json.JSONDecodeError, ValueError):
        return None
    if doc is None:
        return None

    if (
        len(argv) >= 5
        and argv[0].lower() == "power"
        and argv[2].lower() == "fiber-port"
        and argv[4].lower() in ("on", "off")
    ):
        try:
            fid = int(argv[3])
        except ValueError:
            return None
        node = FiberRadioPort.from_port_id(doc, fid).ssh_node()
        if node:
            return node.invoke(
                ["power", "fiber-port", str(fid), argv[4].lower()],
                defer=False,
            )

    if len(argv) >= 3 and argv[0].lower() == "fiber" and argv[1].lower() == "chip":
        try:
            fid = int(argv[2])
        except ValueError:
            return None
        node = FiberRadioPort.from_port_id(doc, fid).ssh_node()
        if node:
            print(
                "fiber chip: not forwarded over SSH — radios are PCIe/fiber; use panel calibrate PCIe prompts "
                "or edit fiber_map.json (pcie / sfp_serial). Run fiber chip only for ports mapped locally on this machine.",
                file=sys.stderr,
                flush=True,
            )
            return 2

    if len(argv) >= 3 and argv[0].lower() == "panel":
        sub = argv[1].lower()
        if sub in ("on", "off", "reboot", "reboot-force"):
            try:
                pn = int(argv[2])
            except ValueError:
                return None
            n_slots = effective_panel_slots(doc)
            if pn < 1 or pn > n_slots:
                return None
            node = FiberRadioPort.from_port_id(doc, pn).ssh_node()
            if node:
                return node.invoke(["panel", sub, str(pn)], defer=False)

    return None
