#!/usr/bin/env python3
"""
CMake fragment handling for dh_fortran

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

import click
import dhfortran.debhelper as dh
import dhfortran.compilers as cmplrs
import dhfortran.cli as cli


# TODO:
# Look for INTERFACE_INCLUDE_DIRECTORIES
# Edit file (typically XXX-targets.cmake to XXX-$vendor-targets.cmake
#


# Actions we can do:
# rename references to Fortran libs ( libfckit.so -> libfckit-gfortran.so)
# rename FMODDIR


##
## CMake-file -specific interface for debhelper
##
class CMakeFileHelper(dh.DhFortranHelper):

    def __init__(self, options):
        super().__init__(options, "fortran-cmake", "dh_fortran_cmake")

    def can_work_automatically(*cmdline_files: list[str]) -> bool:
        """Called by self.process_and_move_files()
        Can we run automatically, without user configuration?

        If this is true, d.autogenerate_pkg_filelist() needs to be defined
        """
        return False

    def compute_dest(self, srcdire, cmake_file, target_dest=None):
        """Where does cmake file go ? Should be called by base
        DebHelper() to move files"""
        cli.debug_print("compute_dest [cmake] {srcdir}  {cmake_file}")

        # TODO : unsafe for cross-compilation. Build our own flibdir
        flibdir = f"/usr/lib/{dh.multiarch}/fortran"

        if cmake_file is None:
            return flibdir
        if cmake_file.startswith("/"):
            return cmake_file
        else:
            return f"{flibdir}/{cmake_file}"

    def process_file(self, pkg, cmake_file, target_pkg, target_dest=None):
        cli.debug_print(
            f"process_file [lib]  name {cmake_file} {target_pkg} {target_dest}"
        )
        ...


def rewrite_cmake(oldname, newname, cb_dict):
    """Rewrite a cmake file:

    Called by clone_and_rewrite():

    """
    # c
    # INTERFACE_INCLUDE_DIRECTORIES
    #   sed -i -e 's%$${_IMPORT_PREFIX}/lib/libfckit%${LIBDIR}/libfckit%g'
    #            $(TMPDIR)/$(LIBDIR)/cmake/fckit/fckit-targets.cmake
    #   sed -i -e 's%$${_IMPORT_PREFIX}/include%/usr/include/${DEB_HOST_MULTIARCH}%g' \
    # $(TMPDIR)/$(LIBDIR)/cmake/fckit/fckit-targets.cmake
    #   sed -i -e 's%$${_IMPORT_PREFIX}/module%${FMODDIR}%g'         \
    # $(TMPDIR)/$(LIBDIR)/cmake/fckit/fckit-targets.cmake
    cli.verbose_print(f"rewrite_cmake({oldname},{newname} --simplistic form")
    with open(oldname, "r") as f:
        with open(newname, "w") as n:
            n.write(f.read)


@click.command(
    context_settings=dict(
        ignore_unknown_options=False,
    )
)
@click.option("--fc", help="Fortran compiler flavor, eg. gfortran-15", default=None)
@click.argument("files", nargs=-1, type=click.UNPROCESSED)
@cli.debhelper_common_args
def dh_fortran_cmake(files, *args, **kwargs):
    """CMake file handler for dh-fortran

    *dh_fortran_cmake* is a Debhelper plugin script that may be called in the
    installation sequence to update CMake scripts.
    """
    cli.debug_print(f"dh_fortran_cmake called with files {files} kwargs {kwargs}")

    # Get defaults if not defined
    flavor, host_arch = cmplrs.get_fc_flavor_arch(kwargs["fc"])
    kwargs.update(
        {
            "flavor": flavor,
            "vendor": cmplrs.get_abi_vendor(flavor),
        }
    )
    d = CMakeFileHelper(dh.build_options(**kwargs))
    searchdirs = [d.options.tmpdir, "."]
    d.process_and_move_files(searchdirs, *files)


if __name__ == "__main__":
    import pytest

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