# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations

from pathlib import Path

YAML_REGISTRY_PATH = Path(__file__).parent / "metrics_template.yaml"
RST_TABLE_OUTPUT_PATH = "airflow-core/docs/administration-and-deployment/logging-monitoring/metric_tables.rst"


def read_metrics_yaml(yaml_path: str) -> list:
    """
    Read the metrics from a YAML registry file.

    Returns:
        List of metric dictionaries
    """
    from pathlib import Path

    import yaml

    yaml_file = Path(yaml_path)

    if not yaml_file.exists():
        raise FileNotFoundError(f"The provided YAML file doesn't exist: '{yaml_path}'")

    with open(yaml_file) as f:
        data = yaml.safe_load(f)

    return data["metrics"]


def convert_to_rst_tables(metrics: list) -> str:
    """
    Convert a metrics list to RST tables, separated by type.

    Returns:
        RST tables as a string, separated by type (counters, gauges, timers)
    """
    from tabulate import tabulate

    # Group metrics by type
    counters = []
    gauges = []
    timers = []

    for metric in metrics:
        metric_type = metric.get("type", "").lower()
        row = [
            f"``{metric['name']}``",
            f"``{metric.get('legacy_name', '-')}``",
            metric["description"],
        ]

        if metric_type == "counter":
            counters.append(row)
        elif metric_type == "gauge":
            gauges.append(row)
        elif metric_type == "timer":
            timers.append(row)

    headers = ["Name", "Legacy Name", "Description"]

    # Build the output
    output = []

    # Counters section
    if counters:
        output.append("Counters")
        output.append("--------")
        output.append("")
        output.append(tabulate(counters, headers=headers, tablefmt="rst"))
        output.append("")

    # Gauges section
    if gauges:
        output.append("Gauges")
        output.append("------")
        output.append("")
        output.append(tabulate(gauges, headers=headers, tablefmt="rst"))
        output.append("")

    # Timers section
    if timers:
        output.append("Timers")
        output.append("------")
        output.append("")
        output.append(tabulate(timers, headers=headers, tablefmt="rst"))
        output.append("")

    return "\n".join(output)


def write_metric_tables_file(rst_tables_str: str, output_path: str, yaml_source: str):
    """Write the RST tables string to a file."""
    from pathlib import Path

    license_local_var = """ .. Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    \"License\"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

 ..   http://www.apache.org/licenses/LICENSE-2.0

 .. Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
"""

    warning = f""".. WARNING: This file is auto-generated from '{yaml_source}'.
   Do not edit this file manually. Any changes will be overwritten during the next build.
   To modify metrics, edit '{yaml_source}' and rebuild.
"""

    output_file = Path(output_path)

    with open(output_file, "w") as f:
        f.write(license_local_var)
        f.write("\n")
        f.write(warning)
        f.write("\n")
        f.write(rst_tables_str)


def generate_metrics_rst_from_registry():
    metrics_list = read_metrics_yaml(yaml_path=str(YAML_REGISTRY_PATH))

    tables_str = convert_to_rst_tables(metrics=metrics_list)

    write_metric_tables_file(
        rst_tables_str=tables_str, output_path=RST_TABLE_OUTPUT_PATH, yaml_source=str(YAML_REGISTRY_PATH)
    )


class MetricsRegistry:
    """Class for storing and looking up metrics."""

    def __init__(self):
        metrics_list = read_metrics_yaml(yaml_path=str(YAML_REGISTRY_PATH))
        # Convert the list to dict for faster lookup.
        self._metrics = {metric["name"]: metric for metric in metrics_list}

    def get(self, name: str) -> dict | None:
        """Get metric by name."""
        return self._metrics.get(name)
