<?php

declare(strict_types=1);

namespace Package\Library;

use StaticPHP\Attribute\Package\BuildFor;
use StaticPHP\Attribute\Package\Library;
use StaticPHP\Attribute\Package\Validate;
use StaticPHP\DI\ApplicationContext;
use StaticPHP\Exception\EnvironmentException;
use StaticPHP\Package\LibraryPackage;
use StaticPHP\Util\FileSystem;
use StaticPHP\Util\System\WindowsUtil;

#[Library('mpir')]
class mpir
{
    #[Validate]
    public function validate(): void
    {
        $ver = WindowsUtil::findVisualStudio();
        $vs_ver_dir = match ($ver['major_version']) {
            '18', // VS 2026 reuses the build.vc17 solution, which msbuild builds via forward compatibility.
            '17' => '\build.vc17',
            '16' => '\build.vc16',
            default => throw new EnvironmentException("Current VS version {$ver['major_version']} is not supported yet!"),
        };
        ApplicationContext::set('mpir_vs_ver_dir', $vs_ver_dir);
    }

    #[BuildFor('Windows')]
    public function build(LibraryPackage $lib): void
    {
        $vs_ver_dir = ApplicationContext::get('mpir_vs_ver_dir');
        cmd()->cd("{$lib->getSourceDir()}{$vs_ver_dir}\\lib_mpir_gc")
            ->exec('msbuild lib_mpir_gc.vcxproj /t:Rebuild /p:Configuration=Release /p:Platform=x64 /p:WindowsTargetPlatformVersion=10.0');
        FileSystem::createDir($lib->getLibDir());
        FileSystem::createDir($lib->getIncludeDir());
        FileSystem::copy("{$lib->getSourceDir()}{$vs_ver_dir}\\lib_mpir_gc\\x64\\Release\\mpir_a.lib", "{$lib->getLibDir()}\\mpir_a.lib");
        // mpir.h and gmp.h are generated by the prebuild step into the source root
        FileSystem::copy("{$lib->getSourceDir()}\\mpir.h", "{$lib->getIncludeDir()}\\mpir.h");
        FileSystem::copy("{$lib->getSourceDir()}\\gmp.h", "{$lib->getIncludeDir()}\\gmp.h");
    }
}
