#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Add the tested Romulus WCN7850 alias to bdencoder JSON; fail if ambiguous."""
import json
from pathlib import Path
import sys

SOURCE = "bus=pci,vendor=17cb,device=1107,subsystem-vendor=17cb,subsystem-device=3378,qmi-chip-id=2,qmi-board-id=255"
TARGET = SOURCE.replace("subsystem-device=3378", "subsystem-device=1107")


def add_alias(data):
    entries = [entry for group in data for entry in group.get("board", [])]
    if any(TARGET in entry.get("names", []) for entry in entries):
        return False
    matches = [entry for entry in entries if SOURCE in entry.get("names", [])]
    if len(matches) != 1:
        raise ValueError(f"Expected one calibration source, found {len(matches)}")
    matches[0]["names"].append(TARGET)
    return True


if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit("Usage: azurefin-board-alias board-2.json")
    path = Path(sys.argv[1])
    data = json.loads(path.read_text())
    if add_alias(data):
        path.write_text(json.dumps(data, indent=4) + "\n")
