#!/usr/bin/python3
"""
Entry point for dh-fortran command

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

import click
import dhfortran.compilers as cmplrs
import dhfortran.cli as cli
import dhfortran.targets as targets


@click.group()
@click.pass_context
def dh_fortran(ctx):
    # breakpoint()    # ensure that ctx.obj exists and is a dict
    # (in case `cli()` is called by means other than the `if` block below)
    ctx.ensure_object(dict)


@dh_fortran.command("get_fc_flags")
@click.option("--fc", default=None, help="Fortran compiler")
# @cli.debhelper_common_args
def get_fc_flags(fc):
    """
    Returns set of flags to be set , either passed as FCFLAGS to another
    """
    if fc is None:
        fc = cmplrs.get_fc_default()
    cli.validate_compiler(fc)
    flavor,arch = cmplrs.get_fc_flavor_arch(fc)
    click.echo(cmplrs.get_fc_flags(flavor,arch))


@dh_fortran.command("get_f77_flags")
@click.option("--f77", default=None, help="Fortran compiler")
def get_f77_flags(f77):
    """
    Returns flags for a FORTRAN 77 compiler (recommended contents of FFLAGS)
    """
    cli.validate_compiler(f77)
    click.echo(cmplrs.get_f77_flags(f77))


@dh_fortran.command("get_ld_flags")
@click.option("--fc", default=None, help="Fortran compiler")
# @cli.debhelper_common_args
def get_ld_flags(fc):
    """
    Returns set of flags to be set , either passed as FCFLAGS to another
    """
    cli.validate_compiler(fc)
    flavor, arch = cmplrs.get_fc_flavor_arch(fc)
    click.echo(cmplrs.get_ld_flags(flavor, arch))


@dh_fortran.command("get_fc_default", help="Returns default Fortran flavor")
@click.option("--fc", default=None, help="Fortran compiler")
@click.pass_context
def get_fc_default(ctx, fc):
    """
    Details on get_fc_default
    """
    cli.validate_compiler(fc)
    click.echo(cmplrs.get_fc_default(fc))


@dh_fortran.command("get_fc_optional", help="Returns list of optional Fortran flavors")
@click.option("--fc", default=None, help="Fortran compiler")
@click.pass_context
def get_fc_optional(ctx, fc):
    cli.validate_compiler(fc)
    flavor, arch = cmplrs.get_fc_flavor_arch(fc)
    click.echo(" ".join(cmplrs.get_fc_optional(flavor)))


@dh_fortran.command("get_flibdir", help="Returns flibdir for a given compiler")
@click.pass_context
@click.option("--fc", default=None, help="Fortran compiler (eg gfortran-15, flang-21")
@click.option(
    "--prepend",
    "-L",
    help="Prepend -L to directories as needed",
    is_flag=True,
    default=False,
)
def get_flibdir(ctx, fc, prepend):
    cli.validate_compiler(fc)
    flavor, arch = cmplrs.get_fc_flavor_arch(fc)
    prefix = "-L" if prepend else ""
    click.echo(f"{prefix}{cmplrs.get_flibdir(flavor,arch)}")


@dh_fortran.command(
    "get_flibdirs", help="Returns compatible flibdirs for a given compiler"
)
@click.pass_context
@click.option("--fc", default=None, help="Fortran compiler (eg gfortran-15, flang-21")
@click.option(
    "--prepend",
    "-L",
    help="Prepend -L to directories as needed",
    is_flag=True,
    default=False,
)
def get_flibdirs(ctx, fc, prepend):
    cli.validate_compiler(fc)
    flavor, arch = cmplrs.get_fc_flavor_arch(fc)
    libdirs = cmplrs.get_flibdirs(flavor, arch)
    prefix = "-L" if prepend else ""
    click.echo(" ".join([f"{prefix}{fl}" for fl in libdirs]))


@dh_fortran.command("get_fmoddir", help="Returns fmoddir for a given compiler")
@click.option("--fc", default=None, help="Fortran compiler")
@click.option("--flavor", help="Fortran flavor (eg gfortran-15, flang-21)")
#              deprecate="--flavor is deprecated in favour of --fc")
@click.option(
    "--prepend",
    "-I",
    help="Prepend -I or -M to directories as needed",
    is_flag=True,
    default=False,
)
@click.pass_context
def get_fmoddir(ctx, flavor, fc, prepend):
    cli.validate_compiler(fc)
    flavor, arch = cmplrs.get_fc_flavor_arch(flavor if fc is None else fc)
    # May be "-I" or "-module " depending on compiler
    prefix = ""
    if prepend:
        prefix = (
            cmplrs.compilers[flavor]["mod_arg"]
            if "mod_arg" in cmplrs.compilers[flavor]
            else "-I"
        )
    click.echo(f"{prefix}{cmplrs.get_fmoddir(flavor,arch)}")


@dh_fortran.command(
    "get_fmoddirs", help="Returns compatible fmoddirs for a given compiler"
)
@click.option("--fc", help="Fortran compiler (eg gfortran-15, flang-21)")
@click.option(
    "--prepend",
    "-I",
    help="Prepend -I or -M to directories as needed",
    is_flag=True,
    default=False,
)
@click.pass_context
def get_fmoddirs(ctx, fc, prepend):
    cli.validate_compiler(fc)
    flavor, arch = cmplrs.get_fc_flavor_arch(fc)
    # TODO. May be "-I" or "-M" depending on compiler
    moddirs = cmplrs.get_fmoddirs(flavor, arch)
    prefix = ""
    if prepend:
        prefix = (
            cmplrs.compilers[flavor]["mod_arg"]
            if "mod_arg" in cmplrs.compilers[flavor]
            else "-I"
        )
    click.echo(" ".join([f"{prefix}{moddir}" for moddir in moddirs]))


@dh_fortran.command(
    "get_fc_exe",
    help="Return Fortran executable for specified (or default) flavor",
    deprecated="MAY BE  DEPRECATED IN FINAL API",
)
@click.option("--flavor", help="Fortran flavor (eg gfortran-15, flang-21)")
@click.pass_context
def get_fc_exe(ctx, flavor):
    cli.validate_flavor(flavor)
    click.echo(cmplrs.get_fc_exe(flavor))


@dh_fortran.command("get_abi_vendor", help="Returns ABI name for a given compiler")
@click.option("--fc", help="Fortran compiler  (eg gfortran-15, flang-21)")
@click.pass_context
def get_abi_vendor(ctx, fc):
    cli.validate_compiler(fc)
    flavor, arch = cmplrs.get_fc_flavor_arch(fc)
    click.echo(cmplrs.get_abi_vendor(flavor))


@dh_fortran.command(
    "get_env",
    help="Return set of environment flags to execute  debian/rules targets with",
)
@click.option("--fc", default=None, help="Fortran compiler")
@click.option("--save", default=False, is_flag=True, hidden=True)
def get_env(fc: str, save: bool):
    cli.validate_compiler(fc)
    if fc and not cmplrs.compiler_present(fc):
        raise click.UsageError(Exception(f"Compiler {fc} not on PATH; is it installed?"))

    flavor, arch = cmplrs.get_fc_flavor_arch(fc)
    if save:
        with open(".debhelper/fc_env", "w") as f:
            print(cmplrs.get_env(flavor), file=f)
    else:
        click.echo(cmplrs.get_env(flavor))


##
## debian/rules targets
##


@cli.debhelper_common_args
@dh_fortran.command("clean", help="Execute Fortran-specific clean actions")
def clean():
    targets.clean()


@cli.debhelper_common_args
@dh_fortran.command(
    "configure", help="Execute configure actions for each Fortran flavor"
)
def configure(*args, **kwargs):
    targets.configure()


# Test handling of common debhelper stuff
@cli.debhelper_common_args
@dh_fortran.command("build", help="Execute build target for each Fortran flavor")
def build():
    targets.build()


@cli.debhelper_common_args
@dh_fortran.command("install", help="Execute install target for each Fortran flavor")
def install():
    targets.install()


@cli.debhelper_common_args
@dh_fortran.command("test", help="Execute test target for each Fortran flavor")
def test():
    targets.test()


if __name__ == "__main__":
    import pytest

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