from __future__ import annotations

from pathlib import Path
from typing import Any

from setup.julia_setup import _jl


def authenticate_github(token: str) -> Any:
    """Authenticate with GitHub using MacroEnergy.jl."""
    macroenergy = _macroenergy_module()
    return macroenergy.authenticate_github(token)


def list_examples(*, auth: Any = None) -> list[str]:
    """Call MacroEnergy.jl list_examples(; auth=...) and return names."""
    macroenergy = _macroenergy_module()
    result = _call_with_optional_auth(macroenergy.list_examples, auth=auth)
    return [str(item) for item in result]


def download_example(
    example_name: str,
    target_dir: str | Path = ".",
    *,
    auth: Any = None,
) -> None:
    """Call MacroEnergy.jl download_example(example_name, target_dir; auth=...)."""
    macroenergy = _macroenergy_module()
    _call_with_optional_auth(
        macroenergy.download_example,
        str(example_name),
        str(target_dir),
        auth=auth,
    )


def download_examples(
    target_dir: str | Path = ".",
    pause_seconds: float = 1.0,
    *,
    auth: Any = None,
) -> None:
    """Call MacroEnergy.jl download_examples(target_dir, pause_seconds; auth=...)."""
    macroenergy = _macroenergy_module()
    _call_with_optional_auth(
        macroenergy.download_examples,
        str(target_dir),
        float(pause_seconds),
        auth=auth,
    )


def example_readme(example_name: str, *, auth: Any = None) -> None:
    """Call MacroEnergy.jl example_readme(example_name; auth=...)."""
    macroenergy = _macroenergy_module()
    _call_with_optional_auth(macroenergy.example_readme, str(example_name), auth=auth)


def example_contents(example_name: str, *, auth: Any = None) -> None:
    """Call MacroEnergy.jl example_contents(example_name; auth=...)."""
    macroenergy = _macroenergy_module()
    _call_with_optional_auth(macroenergy.example_contents, str(example_name), auth=auth)


def _macroenergy_module() -> Any:
    jl = _jl()
    jl.seval("using MacroEnergy")
    return jl.MacroEnergy


def _call_with_optional_auth(func: Any, *args: Any, auth: Any = None) -> Any:
    if auth is None:
        return func(*args)
    return func(*args, auth=auth)
