#!/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

# cmakedir = f"{cli.libdir}/cmake"


# 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 compute_dest(self, srcdire, cmake_file, target_dest=None):
        """Where does cmake file go ? Should be called by base DebHelper() to move files"""
        cli.verbose_print("DEBUG compute_dest [cmake] {srcdir}  {cmake_file}")

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

    def process_file(self, pkg, cmake_file, target_pkg, target_dest=None):
        cli.verbose_print(
            f"DEBUG 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=True,
    )
)
@click.option("--flavor", 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.verbose_print(f"dh_fortran_cmake called with files {files} kwargs {kwargs}")
    cli.validate_flavor(kwargs["flavor"])

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


if __name__ == "__main__":
    import pytest

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