import json

import requests

from tfcommander.config import get_consul_ip
from tfcommander.exceptions import ConnectionError

DEFAULT_API_PORT = 8087
DEFAULT_TIMEOUT = 10


def list_routers(public_ip: str, api_port: int = DEFAULT_API_PORT) -> None:
    internal_ip = get_consul_ip(public_ip)
    url = f"http://{internal_ip}:{api_port}/api/http/routers"

    try:
        resp = requests.get(url, timeout=DEFAULT_TIMEOUT)
    except requests.exceptions.RequestException as e:
        raise ConnectionError(internal_ip, e)

    routers = resp.json()
    print(f"Routers in Traefik at {internal_ip}:")
    print("-" * 67)

    router_items = (
        routers.items()
        if isinstance(routers, dict)
        else [(r.get("name", "unknown"), r) for r in routers]
    )

    for router_name, router_data in router_items:
        print(f"Router: {router_name}")
        print(f"  Rule: {router_data.get('rule', '')}")
        print(f"  Service: {router_data.get('service', '')}")
        middlewares = router_data.get("middlewares", [])
        if middlewares:
            print(f"  Middlewares: {', '.join(middlewares)}")
        print("-" * 67)


def list_middlewares(public_ip: str, api_port: int = DEFAULT_API_PORT) -> None:
    internal_ip = get_consul_ip(public_ip)
    url = f"http://{internal_ip}:{api_port}/api/http/middlewares"

    try:
        resp = requests.get(url, timeout=DEFAULT_TIMEOUT)
    except requests.exceptions.RequestException as e:
        raise ConnectionError(internal_ip, e)

    middlewares = resp.json()
    print(f"Middlewares in Traefik at {internal_ip}:")
    print("-" * 67)
    for mw in middlewares:
        for key, value in mw.items():
            if isinstance(value, (dict, list)):
                print(f"{key}: {json.dumps(value, indent=2)}")
            else:
                print(f"{key}: {value}")
        print("-" * 67)
