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

import json
import sys

from hubmgr.constants import PANEL_SLOTS
from hubmgr import fiber_map_io as fm
from hubmgr import remote_ssh as rs


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.
    """
    rs.apply_remote_ssh_env_file()
    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
        entry = doc["fiber_ports"].get(str(fid))
        ssh = fm.fiber_ssh_target(entry) if isinstance(entry, dict) else None
        if ssh:
            return rs.ssh_forward(ssh, ["power", "fiber-port", str(fid), argv[4].lower()])

    if len(argv) >= 3 and argv[0].lower() == "fiber" and argv[1].lower() == "chip":
        try:
            fid = int(argv[2])
        except ValueError:
            return None
        entry = doc["fiber_ports"].get(str(fid))
        ssh = fm.fiber_ssh_target(entry) if isinstance(entry, dict) else None
        if ssh:
            extra = ["save"] if len(argv) >= 4 and argv[3].lower() == "save" else []
            return rs.ssh_forward(ssh, ["fiber", "chip", str(fid), *extra])

    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
            if pn < 1 or pn > PANEL_SLOTS:
                return None
            entry = doc["fiber_ports"].get(str(pn))
            ssh = fm.fiber_ssh_target(entry) if isinstance(entry, dict) else None
            if ssh:
                return rs.ssh_forward(ssh, ["panel", sub, str(pn)])

    return None
