use strict;
use warnings;
use alienfile;
use Config;
use File::Copy qw(copy);
use File::Path qw(make_path);
use File::Spec;
use File::Temp ();
use Text::ParseWords ();

# Register the CMake gather BEFORE PkgConfig's command-sequence gather.
# A command-sequence hook can return success after its internal probe
# mismatch has been consumed by another hook. The code hook below instead
# throws on a non-CMake installation, allowing PkgConfig to gather normally.
sys {
    gather sub {
        my ($build) = @_;
        my $config = $build->install_prop->{rmlui_cmake}
            or die 'CMake system discovery did not return configuration';
        for my $key (keys %$config) {
            $build->runtime_prop->{$key} = $config->{$key};
        }
        return 1;
    };
};

# A system package must provide both core and debugger through this module.
# Upstream currently supplies CMake metadata but not a .pc file.
plugin 'PkgConfig' => (
    pkg_name      => 'rmlui',
    exact_version => '6.3',
);


# The upstream package exports CMake targets but no pkg-config file.
# Keep the existing pkg-config probe first. This fallback uses the exact
# usage requirements generated by CMake for a real executable.
configure {
    requires 'File::Which';
};

sub rmlui_cmake_probe {
    my ($build) = @_;
    # Unix Makefiles and GNU-style library flags are the supported fallback.
    return unless $^O eq 'linux';
    require File::Which;
    my $cmake = File::Which::which('cmake') or return;
    my $dir = File::Temp::tempdir(CLEANUP => 1);
    my $write = sub {
        my ($name, $content) = @_;
        open my $fh, '>', File::Spec->catfile($dir, $name) or die $!;
        print {$fh} $content;
        close $fh or die $!;
    };
    $write->('CMakeLists.txt', <<'CMAKE');
cmake_minimum_required(VERSION 3.16)
project(AlienRmlUiProbe LANGUAGES CXX)
find_package(RmlUi 6.3 EXACT CONFIG REQUIRED)
if(NOT RMLUI_FONT_ENGINE STREQUAL "freetype")
    message(FATAL_ERROR "RmlUi must use the FreeType font engine")
endif()
add_executable(rmlui_probe smoke.cpp)
set_target_properties(rmlui_probe PROPERTIES
    CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES CXX_EXTENSIONS NO)
target_link_libraries(rmlui_probe PRIVATE RmlUi::Core RmlUi::Debugger)
CMAKE
    $write->('smoke.cpp', <<'CPP');
#include <RmlUi/Core.h>
#include <RmlUi/Debugger.h>
int main() {
    if (Rml::GetVersion() != "6.3" || !Rml::Initialise()) return 1;
    const bool ok = Rml::GetNumContexts() == 0 && !Rml::Debugger::IsVisible();
    Rml::Shutdown();
    return ok ? 0 : 1;
}
CPP
    my $bin = File::Spec->catdir($dir, 'build');
    return if system($cmake, '-S', $dir, '-B', $bin, '-G', 'Unix Makefiles',
        '-DCMAKE_BUILD_TYPE=Release', '-DCMAKE_CXX_FLAGS_RELEASE:STRING=',
        '-DCMAKE_LINK_DEPENDS_USE_LINKER=OFF') != 0;
    return if system($cmake, '--build', $bin, '--config', 'Release') != 0;
    return if system(File::Spec->catfile($bin, 'rmlui_probe')) != 0;

    # Read only the compile and link arguments for this single target.
    # The probe intentionally rejects unfamiliar linker syntax rather
    # than returning flags that a downstream XS build cannot use.
    my $target = File::Spec->catdir($bin, 'CMakeFiles', 'rmlui_probe.dir');
    my $read = sub {
        my ($name) = @_;
        open my $fh, '<', File::Spec->catfile($target, $name) or die $!;
        local $/;
        return <$fh>;
    };
    my $flags = $read->('flags.make');
    my @cflags;
    for my $key (qw(CXX_DEFINES CXX_INCLUDES CXX_FLAGS)) {
        my ($value) = $flags =~ /^\Q$key\E[ \t]*=[ \t]*(.*)$/m;
        push @cflags, Text::ParseWords::shellwords($value // '');
    }
    push @cflags, '-std=c++17' unless grep /^-std=/, @cflags;
    my @command = Text::ParseWords::shellwords($read->('link.txt'));
    shift @command; # C++ compiler
    my (@dirs, @libs, @options);
    my $saw_object = 0;
    while (@command) {
        my $arg = shift @command;
        if ($arg eq '-o') {
            shift @command;
        } elsif ($arg =~ m{(?:^|/)smoke\.cpp\.o$}) {
            $saw_object = 1;
        } elsif ($arg =~ m{^(/.*)/(lib[^/]+\.(?:a|so(?:\.[0-9]+)*))$}) {
            # GNU ld's exact-filename syntax preserves static/shared selection.
            push @dirs, "-L$1";
            push @libs, "-l:$2";
        } elsif ($arg =~ /^-L./) {
            push @dirs, $arg;
        } elsif ($arg =~ /^-l./) {
            push @libs, $arg;
        } elsif ($arg =~ /^-Wl,--dependency-file(?:=|,)/) {
            # CMake's dependency tracking is local to the probe build.
            # Never export a linker output path to a downstream consumer.
            next;
        } elsif ($arg =~ /^(?:-Wl,|-pthread$|-fuse-ld=)/) {
            push @options, $arg;
        } else {
            $build->log("Unsupported CMake link argument: $arg");
            return;
        }
    }
    return unless $saw_object && @libs;
    # Quoting must survive Alien::Base and Test::Alien shellwords parsing.
    # Reject paths containing whitespace or shell metacharacters for now.
    my @all = (@cflags, @dirs, @options, @libs);
    return if grep /[\s'"\\\x00]/, @all;
    my %seen;
    @dirs = grep { !$seen{$_}++ } @dirs;
    my $cflags = join ' ', @cflags;
    my $libs = join ' ', @dirs, @options, @libs;
    return {
        version => '6.3', cflags => $cflags, libs => $libs,
        cflags_static => $cflags, libs_static => $libs,
        discovery => 'cmake',
    };
}

probe sub {
    my ($build) = @_;
    delete $build->install_prop->{rmlui_cmake};
    my $config = rmlui_cmake_probe($build) or return 'share';
    $build->install_prop->{rmlui_cmake} = $config;
    return 'system';
};

share {
    requires 'Alien::FreeType' => '0.01';
    start_url 'https://github.com/mikke89/RmlUi/archive/refs/tags/6.3.tar.gz';
    # Published by xmake-repo in packages/r/rmlui/xmake.lua.
    digest SHA256 => 'd977298bb6147610e5984d5db85ddf284020d655a8713913f6982074f1dbdede';
    plugin 'Download';
    plugin 'Extract' => 'tar.gz';
    plugin 'Build::CMake';
    meta_prop->{out_of_source} = 1;
    # Keep CMake output and generated metadata in the same staged prefix.
    # Alien::Build relocates the flags to the installed share directory.
    meta_prop->{destdir} = 0;

    before build => sub {
        my ($build) = @_;
        # Alien::Build supplies dependency pkg-config search paths.
        # CMake's FindFreetype also needs the bundled native prefix.
        if (Alien::FreeType->install_type eq 'share') {
            my $prefix = Alien::FreeType->dist_dir;
            $ENV{FREETYPE_ROOT} = $prefix;
            $ENV{CMAKE_PREFIX_PATH} = join $Config{path_sep},
                $prefix, grep { length } ($ENV{CMAKE_PREFIX_PATH} // '');
            $build->runtime_prop->{freetype_prefix} = $prefix;
            $build->log("Using bundled Alien::FreeType: $prefix");
        }
    };

    build [
        [ '%{cmake}', @{ meta->prop->{plugin_build_cmake}{args} },
          '-DCMAKE_BUILD_TYPE=Release',
          '-DBUILD_SHARED_LIBS=OFF',
          '-DCMAKE_POSITION_INDEPENDENT_CODE=ON',
          '-DCMAKE_INSTALL_LIBDIR=lib',
          '-DBUILD_TESTING=OFF',
          '-DRMLUI_SAMPLES=OFF',
          '-DRMLUI_LUA_BINDINGS=OFF',
          '-DRMLUI_SVG_PLUGIN=OFF',
          '-DRMLUI_LOTTIE_PLUGIN=OFF',
          '-DRMLUI_FONT_ENGINE=freetype',
          '%{.install.extract}' ],
        '%{make}',
        '%{make} install',
    ];

    after build => sub {
        my ($build) = @_;
        if (my $ft = $build->runtime_prop->{freetype_prefix}) {
            open my $cache, '<', 'CMakeCache.txt' or die "Cannot read CMakeCache.txt: $!";
            my $text = do { local $/; <$cache> };
            close $cache;
            for my $key (qw(FREETYPE_INCLUDE_DIR_freetype2 FREETYPE_INCLUDE_DIR_ft2build FREETYPE_LIBRARY_RELEASE)) {
                my ($value) = $text =~ /^\Q$key\E:[^=]+=(.*)$/m;
                die "CMake did not use Alien::FreeType for $key: " . ($value // 'missing') . "\n"
                    unless defined $value && index($value, "$ft/") == 0;
            }
        }
        my $prefix = $build->install_prop->{prefix};
        my $source = $build->install_prop->{extract};
        my $pcdir = File::Spec->catdir($prefix, 'lib', 'pkgconfig');
        my $licenses = File::Spec->catdir($prefix, 'share', 'licenses', 'RmlUi');
        make_path($pcdir, $licenses);
        for my $entry (
            ['LICENSE.txt', 'LICENSE.txt'],
            ['Include/RmlUi/Core/Containers/LICENSE.txt', 'LICENSE.Core.ThirdParty.txt'],
            ['Source/Debugger/LICENSE.txt', 'LICENSE.Debugger.ThirdParty.txt'],
        ) {
            copy(File::Spec->catfile($source, split m{/}, $entry->[0]),
                 File::Spec->catfile($licenses, $entry->[1]))
                or die "Cannot install $entry->[0]: $!";
        }

        # This metadata describes our static build, not arbitrary upstream builds.
        # C++ compilation/linking must use the same toolchain as RmlUi.
        open my $pc, '>', File::Spec->catfile($pcdir, 'rmlui.pc') or die $!;
        print {$pc} <<'PC';
prefix=${pcfiledir}/../..
libdir=${prefix}/lib
includedir=${prefix}/include

Name: RmlUi
Description: RmlUi core and debugger
Version: 6.3
Requires: freetype2
Libs: -L${libdir} -lrmlui_debugger -lrmlui
Cflags: -I${includedir} -DRMLUI_STATIC_LIB -std=c++17
PC
        close $pc or die $!;
        for my $header ('Core.h', 'Debugger.h') {
            my $path = File::Spec->catfile($prefix, 'include', 'RmlUi', $header);
            die "Missing installed RmlUi header: $path" unless -f $path;
        }
    };

};

# Both installation paths must produce usable metadata. In particular,
# a failed pkg-config command sequence must not silently finish the build.
after gather => sub {
    my ($build) = @_;
    my $prop = $build->runtime_prop;
    for my $key (qw(cflags libs version)) {
        die "RmlUi gather did not provide $key. "
            . "For a custom pkg-config installation, export PKG_CONFIG_PATH "
            . "before configuring and keep it set during make.\n"
            unless defined $prop->{$key} && $prop->{$key} =~ /\S/;
    }
    die "Unexpected RmlUi version: $prop->{version}"
        unless $prop->{version} eq '6.3';
};
