#! /usr/bin/python

import argparse
from typing import Any, Dict, Optional
import os
import json
from pathlib import Path
from utils.mikado_set_ip_config.connection_mapping import (
    get_mac_mapping,
    get_controller_mapping,
)
from utils.mikado_set_ip_config.utils import (
    find_template_dir,
    choose_from_list,
    read_assistant_version_string,
    read_json,
)


def set_ip_config(ip_config: Optional[Dict[str, Dict[str, str]]] = None):
    if ip_config is None:
        print("Setting up new network connections from templates")

    controller_version, name_to_logical, success = get_controller_mapping()
    if not success:
        print(
            "Aborting. Could not match controller build year to a matching logical mapping. New controller?"
        )
        return
    print(f"Controller version is: '{controller_version}'")
    logical_to_mac = get_mac_mapping()

    conn_template_path = find_template_dir()
    if conn_template_path is None:
        print("Aborting. Connection templates directory not found.")
        return

    unkown_adapters = []
    sys_conn_path = Path("/etc/NetworkManager/system-connections")
    for connection in name_to_logical.keys():
        con_file = conn_template_path.joinpath(f"{connection}.nmconnection").absolute()
        with open(str(con_file), "r") as file:
            content = file.readlines()

        logical_name = name_to_logical[con_file.stem]
        if logical_name not in logical_to_mac:
            unkown_adapters.append(logical_name)
            continue

        mac = logical_to_mac[logical_name]

        for i, line in enumerate(content):
            if line.startswith("mac-address"):
                content[i] = "mac-address=" + mac + "\n"
            if ip_config is not None and line.startswith("[ipv4]"):
                ip = ip_config[logical_name]["ip"]
                if ip == "dhcp":
                    continue
                content[i + 1] = f"address1={ip}/24"
                content[i + 2] = "method=manual"

        filename = str(sys_conn_path / con_file.name)

        with open(filename, "w") as file:
            file.write("".join(content))
        os.chmod(filename, 0o600)

    for con_file in Path("/run/NetworkManager/system-connections/").glob(
        "*.nmconnection"
    ):
        con_file.unlink()

    if unkown_adapters != []:
        print(
            f"Can not find Ethernet-adapters {', '.join(unkown_adapters)} in current system."
        )
        print("Known logical names are:", ", ".join(logical_to_mac.keys()))
        print("Please setup network connections by hand. New controller type?")
        return

    print("Successfully setup new network settings!")
    return


def _read_hardware_json(folder_path: Path):
    """Read JSON file from config/.system_hardware_info.json in the folder."""
    json_path = folder_path / "config" / ".system_hardware_info.json"
    if not json_path.is_file():
        print(f"No Network config file found at {str(json_path)}.")
        print(
            f"Network config will be tracked for Mikado cells created with Mikado Assistant > 3.3.0. Yours is: {read_assistant_version_string(folder_path)}"
        )
        return None

    return read_json(json_path)


def _format_network_summary(network_dict: Dict[str, Any]):
    """Create a short summary string of the network config."""
    summary = []
    for iface, info in network_dict.items():
        ip = info.get("ip", "unknown")
        summary.append(f"\n\t\t{iface}: {ip}")
    return "; ".join(summary)


def main():
    parser = argparse.ArgumentParser(description="Setup or restore network settings")
    parser.add_argument(
        "--new", action="store_true", help="Setup new controller (non-interactive)"
    )
    args = parser.parse_args()

    # Directory relative to home
    base_dir = Path.home() / "mikado/cells"  # change as needed

    if args.new:
        set_ip_config()
        return

    setup_options = ["Setup new controller", "Restore config from cell"]
    selected_option = choose_from_list(
        setup_options, "Select an option for network setup"
    )
    if selected_option is None:
        print("Aborting.")
        return
    if selected_option == setup_options[0]:
        set_ip_config()
    else:
        # Step 1: choose folder
        folders = sorted([path.stem for path in base_dir.glob("*/") if path.is_dir()])
        selected_folder = choose_from_list(folders, "Select a cell:")
        if selected_folder is None:
            print("Aborting. No cell selected.")
            return

        folder_path = Path(base_dir) / selected_folder

        # Step 2: read JSON and choose timestamp
        hardware_data = _read_hardware_json(folder_path)
        if hardware_data is None:
            print("Aborting. Unable to read hardware info json.")
            return

        # Create a list of display strings combining timestamp + network summary
        timestamps_sorted = sorted(hardware_data.keys(), reverse=True)
        display_items = [
            f"{ts} : {_format_network_summary(hardware_data[ts].get('network', {}))}"
            for ts in timestamps_sorted
        ]

        selected_display = choose_from_list(
            display_items, "Select a timestamp and network config:"
        )
        if selected_display is None:
            print("Aborting.")
            return

        # Extract the timestamp from the selected string
        selected_timestamp = selected_display.split(" : ")[0]

        # Step 3: display selected hardware info
        print("\nSelected network config:")
        print(json.dumps(hardware_data[selected_timestamp]["network"], indent=4))

        set_ip_config(hardware_data[selected_timestamp]["network"])


if __name__ == "__main__":
    main()
