#!/usr/bin/python3
"""
Driver for dh-fortran d/rules targets

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

from dhfortran.compilers import get_fc_optional
from subprocess import check_output
import dhfortran.cli as cli
from os.path import exists
from functools import wraps


def foreach_compiler(fail_on_error_on_default=True):

    def outer(f):
        @wraps(f)
        def inner(*args, **kwargs):
            try:
                verbose_print(
                    f"Calling {f.__name__} with {fc_default()}"
                )  # Pre-function execution
                f(flavor=fc_default(), *args, **kwargs)
            except Exception as ex:
                if fail_on_error_on_default:
                    raise
            for flavor in get_fc_optional():
                try:
                    cli.verbose_print(
                        f"Calling {f.__name__} with {flavor}"
                    )  # Pre-function execution
                    f(flavor)
                except Exception as ex:
                    cli.verbose_print(f"{f.__name__}: ignoring error {ex}")

        return inner

    return outer


# @foreach_compiler(fail_on_error_on_default=False)
def clean(flavor: str = None):
    """Do Fortran-specific operations on d/rules clean target"""
    cli.verbose_print("dh_fortran clean called")
    if exists("fpm.toml"):
        # TODO: Call fpm clean as relevant
        cli.verbose_print("fpm clean")
        check_output(["fpm", "clean"])
    else:
        cli.verbose_print("no fpm.toml")


# @foreach_compiler
def install(flavor: str = None):
    """Do Fortran-specific operations on d/rules install target"""
    cli.verbose_print("dh_fortran install called")
    if exists("fpm.toml"):
        check_output(["fpm", "install"])


# @foreach_compiler
def configure(flavor: str = None):
    """Do Fortran-specific operations on d/rules configure target"""
    cli.verbose_print("dh_fortran configure called")


# @foreach_compiler
def build(flavor: str = None):
    """Do Fortran-specific operations on d/rules build target"""
    cli.verbose_print("dh_fortran build called")
    if exists("fpm.toml"):
        check_output(["fpm", "build"])
        # TODO: Call fpm build as relevant


# @foreach_compiler
def test(flavor: str = None):
    """Do Fortran-specific operations on d/rules test target"""
    cli.verbose_print("dh_fortran test called")
    if exists("fpm.toml"):
        check_output(["fpm", "test"])


if __name__ == "__main__":
    import pytest

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