#!/usr/bin/env python3
# encoding: utf-8

"""

Modified based on the version created for Urgap (https://github.com/urgap/urgap)

"""

import logging
from pathlib import Path


def source_sphinx(inc, path_to_inc):
    return f"""

.. autofunction:: {inc.replace(".inc", "")}.main
    :noindex:

.. include:: {Path(str(path_to_inc).removeprefix("source/"))}    
    
    """


def main():
    # logging.info(
    #     f"Formatting example scripts from {example_script_path} into rst files for docs"
    # )
    example_path = (
        Path(f"{__file__}").parent.resolve() / ".." / "example_scripts"
    ).resolve()
    rst_data = {}
    for example_file in example_path.glob("**/*.py"):
        doc_path = Path("source/code_inc")
        sub_folder_structure = example_file.parts[
            example_file.parts.index("example_scripts") + 1 : -1
        ]
        for part in sub_folder_structure:
            doc_path = doc_path / part

        doc_path.mkdir(parents=True, exist_ok=True)

        basename = example_file.with_suffix(".inc").name
        current_level = rst_data
        for subfolder in sub_folder_structure:
            if subfolder not in current_level.keys():
                current_level[subfolder] = {}
            current_level = current_level[subfolder]

        current_level[basename] = doc_path / basename
        msg = f"Writing {current_level[basename]}"
        logging.info(msg)
        with open(Path(__file__).resolve().parent / doc_path / basename, "w") as o:
            print(""".. code-block:: python\n""", file=o)
            with open(example_file) as infile:
                for line in infile:
                    print("\t{0}".format(line.rstrip()), file=o)

    def plot(current_level=1, current_dict=None, file=None):
        level_to_sphinx = {
            1: "=",
            2: "-",
            3: '"',
        }
        for h1 in current_dict.keys():
            if h1.endswith(".inc"):
                print(source_sphinx(h1, current_dict[h1]), file=file)
            else:
                print(h1, file=e)
                print(level_to_sphinx[current_level] * len(h1), file=e)
                print("", file=e)
                plot(
                    current_level=current_level + 1,
                    current_dict=current_dict[h1],
                    file=file,
                )

    with open("source/example_scripts.rst", "w") as e:
        print(
            """.. _example_scripts:

Example Scripts
###############

The following Jupyter notebooks and example scripts demonstrate the core capabilities of urgap.
Each notebook is self-contained and can be run interactively — start with the credential manager
to understand how urgap handles secrets, then proceed through file handling, reporting, telemetry,
and finally a full pipeline execution. The notebooks are located in the ``docs/tutorial/``
directory of the repository.

Tutorial Notebooks
==================

.. toctree::
   :maxdepth: 1

   tutorial/01_credential_manager
   tutorial/02_ufiles
   tutorial/03_ureport
   tutorial/04_utelemetry
   tutorial/05_pipeline

**01 — Credential Manager**
    Shows how urgap abstracts different secret stores (Azure Key Vault, GCP Secret Manager, ENV
    variables) behind a uniform ``UCredentialManager`` interface. Demonstrates adding credentials
    dynamically and resolving usernames and passwords from a URI.

**02 — UFile and UFileList**
    Introduces the urgap URI scheme and the separation of file *identity* (fragment ``#object``)
    from file *location* (scheme + netloc). Covers initialising ``UFile`` objects, listing files
    with ``UFileList``, and resolving paths across local, cloud, and network backends.

**03 — UReport**
    Demonstrates how to investigate pipeline executions after the fact using ``UReport``.
    Covers listing execution IDs (``wid``, ``node_exe_id``), retrieving execution traces
    (``UTrace``), drawing the execution DAG, and querying output files by node alias.

**04 — UTelemetry**
    Explains urgap's OpenTelemetry integration (``urgap.utl``). Shows how to instrument code
    with counters and nested spans without changing exporter configuration in application code,
    and includes a reference docker-compose setup for a local Jaeger + Prometheus stack.

**05 — Pipeline**
    End-to-end example of initialising ``UFile`` / ``UFileList`` and ``URunDict``, then chaining
    two urgap nodes (``FilterTabularToCSV`` → ``CompressToTar``) into a minimal pipeline.
    Illustrates how urgap's re-run skipping and output versioning work in practice.

""",
            file=e,
        )
        if rst_data:
            print("Additional Example Scripts", file=e)
            print("==========================", file=e)
            print("", file=e)
            plot(current_level=1, current_dict=rst_data, file=e)


if __name__ == "__main__":
    main()
