use alienfile;
use Config;
use File::Spec;
use Path::Tiny qw(path);

my @inc_dirs = (
  '/usr/include',
  '/usr/local/include',
);
my @lib_dirs = (
  '/usr/lib',
  '/usr/local/lib',
  '/usr/lib/x86_64-linux-gnu',
  '/usr/lib/aarch64-linux-gnu',
);

if ($^O eq 'darwin') {
  my $brew = `brew --prefix 2>/dev/null`;
  chomp $brew if defined $brew;
  if ($brew && -d $brew) {
    unshift @inc_dirs, "$brew/include";
    unshift @lib_dirs, "$brew/lib";
  }
} elsif ($^O eq 'MSWin32') {
  my @win_prefixes = (
    ($ENV{VCPKG_INSTALLATION_ROOT}
      ? File::Spec->catdir($ENV{VCPKG_INSTALLATION_ROOT}, 'installed', 'x64-windows')
      : ()),
    'C:/vcpkg/installed/x64-windows',
    'C:/msys64/ucrt64',
    'C:/msys64/mingw64',
  );
  for my $p (@win_prefixes) {
    next unless defined $p && -d $p;
    unshift @inc_dirs, File::Spec->catdir($p, 'include');
    unshift @lib_dirs, File::Spec->catdir($p, 'lib');
  }
}

# Only use PkgConfig on non-Windows systems
if ($^O ne 'MSWin32') {
  plugin PkgConfig => (
    pkg_name => 'libduckdb',
  );
}

# Fallback probe for system/Homebrew/vcpkg/MSYS2 installations without pkg-config
probe sub {
  for my $d (@inc_dirs) {
    return 'system' if -f File::Spec->catfile($d, 'duckdb.h');
  }
  return 'share';
};

# Ensure system installation properties are properly set
meta->around_hook(
  gather_system => sub {
    my ($orig, $build) = @_;
    $orig->($build);

    unless (defined $build->runtime_prop->{version}) {
      my $version;
      if ($^O ne 'MSWin32') {
        $version = `pkg-config --modversion libduckdb 2>/dev/null`;
        if (defined $version && $? == 0) {
          chomp $version;
        } else {
          undef $version;
        }
      }
      $build->runtime_prop->{version} = $version || 'system';
    }

    unless (defined $build->runtime_prop->{cflags}) {
      my $cflags;
      if ($^O ne 'MSWin32') {
        $cflags = `pkg-config --cflags libduckdb 2>/dev/null`;
        if (defined $cflags && $? == 0) {
          chomp $cflags;
        } else {
          undef $cflags;
        }
      }
      if (!defined $cflags) {
        for my $d (@inc_dirs) {
          if (-f File::Spec->catfile($d, 'duckdb.h')) {
            $cflags = "-I$d";
            last;
          }
        }
      }
      $build->runtime_prop->{cflags} = defined $cflags ? $cflags : '-I/usr/include';
    }

    unless (defined $build->runtime_prop->{libs}) {
      my $libs;
      if ($^O ne 'MSWin32') {
        $libs = `pkg-config --libs libduckdb 2>/dev/null`;
        if (defined $libs && $? == 0) {
          chomp $libs;
        } else {
          undef $libs;
        }
      }
      if (!defined $libs) {
        my $lib_flag = '';
        for my $d (@lib_dirs) {
          if (-d $d && $d ne '/usr/lib') {
            $lib_flag .= " -L$d";
          }
        }
        $libs = "$lib_flag -lduckdb";
        $libs =~ s/^\s+//;
      }
      $build->runtime_prop->{libs} = $libs;
    }
  }
);

# Share install: download official prebuilt DuckDB binaries
share {
  my $duckdb_version = '1.5.3';

  my $os = $^O;
  my $arch = '';
  my $binary_suffix;
  my $download_url;

  if ($os eq 'linux') {
    if ($Config{archname} =~ /x86_64|amd64/i) {
      $arch = 'amd64';
    } elsif ($Config{archname} =~ /arm64|aarch64/i) {
      $arch = 'arm64';
    } elsif ($Config{archname} =~ /i[3456]86/i) {
      $arch = 'i386';
    } else {
      $arch = 'amd64';
      log 'Unknown Linux architecture, defaulting to amd64';
    }
    $binary_suffix = 'so';
    $download_url = "https://github.com/duckdb/duckdb/releases/download/v$duckdb_version/libduckdb-linux-$arch.zip";
  } elsif ($os eq 'darwin') {
    $arch = 'universal';
    $download_url = "https://github.com/duckdb/duckdb/releases/download/v$duckdb_version/libduckdb-osx-universal.zip";
    $binary_suffix = 'dylib';
  } elsif ($os eq 'MSWin32') {
    my $is_64bit = $Config{ptrsize} == 8;
    $arch = $is_64bit ? 'amd64' : 'i386';
    $download_url = "https://github.com/duckdb/duckdb/releases/download/v$duckdb_version/libduckdb-windows-$arch.zip";
    $binary_suffix = 'dll';
  } else {
    $binary_suffix = 'so';
    $arch = 'unknown';
  }

  log "Detected platform: $os, architecture: $arch";
  log "Will try binary download from: $download_url";

  plugin 'Download' => (
    url     => $download_url,
    version => $duckdb_version,
  );

  plugin 'Extract' => 'zip';

  build [
    [ 'mkdir', '-p', '%{.install.prefix}/include' ],
    [ 'mkdir', '-p', '%{.install.prefix}/lib' ],
  ];

  after 'build' => sub {
    my ($build) = @_;
    my $extract_dir = $build->install_prop->{extract};

    log "Organizing files from $extract_dir";

    my $prefix      = $build->install_prop->{prefix};
    my $include_dir = path("$prefix/include");
    my $lib_dir     = path("$prefix/lib");
    $include_dir->mkpath;
    $lib_dir->mkpath;

    my $header_count = 0;
    my $lib_count    = 0;
    foreach my $file (path($extract_dir)->children) {
      my $basename = $file->basename;
      if ($basename =~ /\.(h|hpp)$/) {
        path($file)->copy("$include_dir/$basename");
        $header_count++;
      } elsif ($basename =~ /\.(?:$binary_suffix|a|lib)$/i) {
        path($file)->copy("$lib_dir/$basename");
        $lib_count++;
      }
    }

    log "Copied $header_count header files and $lib_count library files to standard locations";

    if ($^O eq 'MSWin32') {
      my $pkgconfig_dir = path("$prefix/lib/pkgconfig");
      $pkgconfig_dir->mkpath;

      my $pc_file    = path("$pkgconfig_dir/libduckdb.pc");
      my $pc_content = <<"EOT";
prefix=$prefix
exec_prefix=\${prefix}
libdir=\${prefix}/lib
includedir=\${prefix}/include

Name: libduckdb
Description: DuckDB database library
Version: $duckdb_version
Cflags: -I\${includedir}
Libs: -L\${libdir} -lduckdb
EOT

      $pc_file->spew($pc_content);
      log "Created pkg-config file: $pc_file";
    }
  };

  meta->around_hook(
    gather_share => sub {
      my ($orig, $build) = @_;
      if ($^O eq 'MSWin32') {
        eval { $orig->($build) };
        if ($@) {
          log 'Original gather_share hook failed, using direct property setting';
        }
      } else {
        $orig->($build);
      }

      my $prefix = $build->install_prop->{prefix};
      log "Setting runtime properties for installation in $prefix";

      $build->runtime_prop->{version} = $duckdb_version;
      $build->runtime_prop->{cflags}  = "-I$prefix/include";
      $build->runtime_prop->{libs}    = "-L$prefix/lib -lduckdb";

      log 'VERSION: ' . $build->runtime_prop->{version};
      log 'CFLAGS: '  . $build->runtime_prop->{cflags};
      log 'LIBS: '    . $build->runtime_prop->{libs};
    },
  );
};
