#!/usr/bin/python3
"""
Support routines for dh-fortran cli commands

Copyright (C) 2025 Alastair McKinstry <mckinstry@debian.org>
Released under the GPL-3 Gnu Public License.
"""

import traceback
import click
from click.exceptions import *
from pathlib import Path
import os
import sys
import dhfortran.compilers as cmplrs
import logging

log = logging.getLogger("dhfortran")

verbose = False


def verbose_print(s: str):
    log.debug(s)
    global verbose
    if verbose:
        click.echo(s)


def warning(s: str):
    log.warning(s)
    click.echo(s, err=True)


def debhelper_common_args(f, minimal=False):

    # Wrapper to add debhelper common args to all targets
    @click.option(
        "--verbose",
        "-v",
        help="show commands that modify the package build directory",
        is_flag=True,
    )
    @click.option("--no-act", help="Don't act, just show the output", is_flag=True)
    @click.option("--indep", "-i", help="Act on all arch-independent packages", is_flag=True)
    @click.option("--arch", "-a", help="Act on all arch-dependent packages", is_flag=True)
    @click.option("--package", "-p", help="Act on named package")
    @click.option("--remaining-packages", help="Act on remaining packages only")
    @click.option("--firstpackage", envvar="FIRSTPACKAGE")
    @click.option("--create-in-sourcedir")
    def wrapper(*args, **kwargs):

        global verbose
        if "DH_VERBOSE" in os.environ:
            verbose = os.environ["DH_VERBOSE"]
        else:
            verbose = kwargs["verbose"]

        try:
            f(*args, **kwargs)
        except Exception as ex:
            if verbose:
                print(traceback.format_exc())
            raise UsageError(ex)

    if not minimal:
        wrapper = click.option("--sourcedir", envvar="SOURCEDIR", default="debian/tmp")(
            wrapper
        )
    #        wrapper = click.option(
    #            "-X", help="Exclude certain packages", envvar="EXCLUDE_FIND"
    #        )(wrapper)
    return wrapper


def validate_flavor(flavor: str) -> None:
    if flavor is None:
        return
    if flavor not in cmplrs.compilers and flavor not in cmplrs.default_compilers:
        raise UsageError(f"{flavor} is not a valid compiler flavor")


def validate_compiler(fc: str) -> None:
    if fc is None:
        return
    f = Path(fc).resolve().name
    for flavor in cmplrs.compilers:
        if f in compilers["flavor"]["exe"]:
            return
    raise UsageError(f"{basename} is not a valid compiler executable")


if __name__ == "__main__":
    import pytest

    pytest.main(["tests/cli.py"])
