import json
import os
from datetime import datetime
from pathlib import Path
from typing import Any

from tfcommander.exceptions import AliasNotFoundError

CONFIG_FILE = os.path.join(Path.home(), ".tfcommander_config.json")


def load_config() -> dict[str, Any]:
    if os.path.exists(CONFIG_FILE):
        with open(CONFIG_FILE, "r") as f:
            return json.load(f)
    return {}


def save_config(config: dict[str, Any]) -> None:
    config["saved_on"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open(CONFIG_FILE, "w") as f:
        json.dump(config, f, indent=4)


def get_consul_ip(public_ip_or_alias: str) -> str:
    config = load_config()
    aliases = config.get("aliases", {})
    internal_ip = aliases.get(public_ip_or_alias)
    if not internal_ip:
        raise AliasNotFoundError(public_ip_or_alias)
    return internal_ip


def add_alias(name: str, ip: str) -> None:
    config = load_config()
    aliases = config.get("aliases", {})
    aliases[name] = ip
    config["aliases"] = aliases
    save_config(config)
    print(f"Alias '{name}' set to {ip}")


def remove_alias(name: str) -> None:
    config = load_config()
    aliases = config.get("aliases", {})
    if name not in aliases:
        raise KeyError(f"No alias named '{name}' found.")
    del aliases[name]
    config["aliases"] = aliases
    save_config(config)
    print(f"Alias '{name}' removed.")


def list_aliases() -> None:
    config = load_config()
    aliases = config.get("aliases", {})
    if aliases:
        print("Configured aliases:")
        for name, ip in aliases.items():
            print(f"  {name}: {ip}")
    else:
        print("No aliases configured.")
