# -*- coding: utf-8 -*-
# Copyright (C) Alexander Pace, Daniel Wysocki (2026)
#
# This file is part of gracedb
#
# gracedb is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# It is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with gracedb.  If not, see <http://www.gnu.org/licenses/>.
"""Utilities for instance-namespaced Kafka topics."""

from urllib.parse import urlparse


def derive_instance_name(service_url):
    """Extract the instance name from a GraceDB service URL.

    The instance name is the first component of the hostname
    (i.e., everything before the first dot, or the full hostname
    if there is no dot).

    Args:
        service_url (str): GraceDB service URL
            (e.g., ``"https://gracedb-dev.ligo.org/api/"``)

    Returns:
        str: Instance name (e.g., ``"gracedb-dev"``)

    Raises:
        ValueError: If the hostname cannot be parsed from the URL

    Examples:
        >>> derive_instance_name("https://gracedb-dev.ligo.org/api/")
        'gracedb-dev'
        >>> derive_instance_name("https://gracedb.ligo.org/api/")
        'gracedb'
        >>> derive_instance_name("https://localhost:8080/api/")
        'localhost'
    """
    parsed = urlparse(service_url)
    hostname = parsed.hostname
    if not hostname:
        raise ValueError(
            f"Cannot parse hostname from URL: {service_url!r}"
        )
    return hostname.split('.')[0]


def make_topic_name(instance_name, pipeline):
    """Build an instance-namespaced Kafka topic name.

    Args:
        instance_name (str): GraceDB instance name
            (e.g., ``"gracedb-dev"``)
        pipeline (str): Pipeline name (e.g., ``"gstlal"``)

    Returns:
        str: Namespaced topic name (e.g., ``"gracedb-dev.gstlal"``)
    """
    return f"{instance_name}.{pipeline}"


def parse_topic_name(namespaced_topic):
    """Split an instance-namespaced topic into its components.

    Args:
        namespaced_topic (str): Namespaced topic name
            (e.g., ``"gracedb-dev.gstlal"``)

    Returns:
        tuple: ``(instance_name, pipeline)``

    Raises:
        ValueError: If the topic does not contain a dot separator
    """
    if '.' not in namespaced_topic:
        raise ValueError(
            f"Topic {namespaced_topic!r} is not namespaced "
            f"(expected 'instance.pipeline' format)"
        )
    instance_name, pipeline = namespaced_topic.split('.', 1)
    return instance_name, pipeline
