import os
import re

import toml


def update_version_in_md(pyproject_path, md_path):
    """Update version number in markdown documentation from pyproject.toml.

    Supports both PEP 621 ([project]) and Poetry ([tool.poetry]) formats.

    Args:
        pyproject_path: Path to pyproject.toml
        md_path: Path to markdown file to update
    """
    with open(pyproject_path, encoding="utf-8") as f:
        data = toml.load(f)

    # Try PEP 621 format first ([project]), then Poetry format ([tool.poetry])
    if "project" in data and "version" in data["project"]:
        version = data["project"]["version"]
    elif (
        "tool" in data
        and "poetry" in data["tool"]
        and "version" in data["tool"]["poetry"]
    ):
        version = data["tool"]["poetry"]["version"]
    else:
        raise ValueError(f"No version found in {pyproject_path}")

    with open(md_path, encoding="utf-8") as f:
        content = f.read()

    # Überschreibe die vorhandene Versionszeile oder füge sie nach der Überschrift ein
    if "**Version:**" in content:
        new_content = re.sub(
            r"(\*\*Version:\*\*.*$)",
            f"**Version:** {version}",
            content,
            count=1,
            flags=re.MULTILINE,
        )
    else:
        new_content = re.sub(
            r"(^# .*$\n)",
            rf"\1\n**Version:** {version}\n",
            content,
            count=1,
            flags=re.MULTILINE,
        )

    with open(md_path, "w", encoding="utf-8") as f:
        f.write(new_content)


def update_versions(*args, **kwargs):
    """MkDocs hook to update version numbers in documentation.

    This function is called by mkdocs-simple-hooks during the build process.
    It reads version numbers from pyproject.toml files and updates
    the corresponding documentation index files.

    Supports both PEP 621 ([project]) and Poetry ([tool.poetry]) formats.
    """
    base_dir = os.path.dirname(os.path.abspath(__file__))
    project_root = os.path.abspath(os.path.join(base_dir, ".."))

    # Update umbrella package documentation (PEP 621 format)
    update_version_in_md(
        os.path.join(project_root, "pyproject.toml"),
        os.path.join(project_root, "docs", "index.md"),
    )

    # Update submodule documentation (PEP 621 format)
    update_version_in_md(
        os.path.join(project_root, "authentication", "pyproject.toml"),
        os.path.join(project_root, "docs", "authentication", "index.md"),
    )
    update_version_in_md(
        os.path.join(
            project_root, "automation", "src", "python-client", "pyproject.toml"
        ),
        os.path.join(project_root, "docs", "automation", "index.md"),
    )
    update_version_in_md(
        os.path.join(project_root, "data", "pyproject.toml"),
        os.path.join(project_root, "docs", "data", "index.md"),
    )
