#!/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 dhfortran.compilers as cmplrs
import traceback
import click
import os
import logging

log = logging.getLogger("dhfortran")

verbose = False
debug = False


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


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


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


# decorator
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(
        "--tmpdir",
        "-P",
        default="debian/tmp",
        help="Use  tmpdir for package build staging directory",
    )
    @click.option(
        "--sourcedir",
        "--sourcedirectory",
        "-D",
        envvar="SOURCEDIR",
        default=".",
        hidden=True,
    )
    @click.option("--builddir", "--builddirectory", "-B", help="Build directory")
    # Ignore the following parameters
    @click.option("-O--no-parallel", is_flag=True, hidden=True)
    @click.option("-O--buildsystem", hidden=True)
    @click.option("-O--builddirectory", hidden=True)
    def wrapper(*args, **kwargs):

        global verbose, debug
        if "DH_VERBOSE" in os.environ:
            verbose = os.environ["DH_VERBOSE"]
        else:
            verbose = kwargs["verbose"] if "verbose" in kwargs else False
        if "DH_DEBUG" in os.environ and os.environ["DH_DEBUG"]:
            debug = True
            verbose = True
        if "o__builddirectory" in kwargs and kwargs["builddir"] is None:
            kwargs["builddir"] = kwargs["o__builddirectory"]

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

    if not minimal:
        # Options that don't apply to dh_fortran helpers, just dh_fortran_*
        wrapper = click.option(
            "--no-act", help="Don't act, just show the output", is_flag=True
        )(wrapper)
        wrapper = click.option("--package", "-p", help="Act on named package")(wrapper)
        wrapper = click.option("--firstpackage", envvar="FIRSTPACKAGE", hidden=True)(
            wrapper
        )
        wrapper = click.option(
            "--indep",
            "-i",
            help="Act on all arch-independent packages",
            is_flag=True,
        )(wrapper)
        wrapper = click.option(
            "--arch", "-a", help="Act on all arch-dependent packages", is_flag=True
        )(wrapper)
        wrapper = click.option(
            "--remaining-packages",
            help="Act on remaining packages only",
            hidden=True,
        )(wrapper)
        wrapper = click.option(
            "--no-package",
            "-N",
            help="Do  not act on the specified package",
            hidden=True,
        )(wrapper)
        wrapper = click.option(
            "--mainpackage", help="Deprecated and unused", hidden=True
        )(wrapper)
        wrapper = click.option("--create-in-sourcedir", hidden=True)(wrapper)
        wrapper = click.option(
            "--exclude_pkgs",
            "-X",
            help="Exclude certain packages",
            envvar="EXCLUDE_FIND",
            hidden=True,
        )(wrapper)

    return wrapper


def validate_flavor(flavor: str) -> None:
    # Validation moved get_fc_flavor_arch does checking
    try:
        flavaor, arch = cmplrs.get_fc_flavor_arch(flavor)
    except Exception as ex:
        raise click.UsageError(ex)


def validate_compiler(fc: str) -> None:
    # Validation moved; get_fc_flavor does checking
    try:
        flavaor, arch = cmplrs.get_fc_flavor_arch(fc)
    except Exception as ex:
        raise click.UsageError(ex)


if __name__ == "__main__":
    import pytest

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