from nebula_cert_manager.hosts import resolve_host_overrides
from nebula_cert_manager.models import HostsConfig, LighthouseConfig


def extract_lighthouses(hosts_config: HostsConfig) -> dict[str, LighthouseConfig]:
    result: dict[str, LighthouseConfig] = {}
    for name, host in hosts_config.hosts.items():
        if host.public_endpoints:
            overrides = resolve_host_overrides(name, hosts_config)
            if overrides.listen_port is None:
                raise ValueError(
                    f"Lighthouse '{name}' has public_endpoints but no listen_port configured"
                )
            result[name] = LighthouseConfig(
                nebula_ip=host.nebula_ip,
                public_endpoints=host.public_endpoints,
                listen_port=overrides.listen_port,
            )
    return result


def resolve_lighthouses_for_client(
    client_name: str, lighthouses: dict[str, LighthouseConfig]
) -> tuple[bool, list[LighthouseConfig]]:
    am_lighthouse = client_name in lighthouses
    filtered = [cfg for name, cfg in lighthouses.items() if name != client_name]
    return am_lighthouse, filtered
