#!/usr/bin/env php
<?php
use Amp\Promise;
use CatPaw\Environment\Attributes\Environment;
use CatPaw\Environment\Attributes\EnvironmentFileName;

use function Amp\File\createDirectoryRecursively;
use function Amp\File\deleteFile;
use function Amp\File\exists;
use function Amp\File\write;
use function CatPaw\deleteDirectoryRecursively;

/**
  * 
  * @param string $name 
  * @param string $entry 
  * @param string $library 
  * @param null|array $ignore 
  * @return Generator<int, Promise<bool>|Promise<void>|Promise<string[]>, mixed, void> 
  * @throws Error 
  */
#[EnvironmentFileName("build.yml")]
function main(
    #[Environment("name")] string $name,
    #[Environment("entry")] string $entry,
    #[Environment("library")] string $library,
    #[Environment("match")] string $match,
){
    $name = str_replace(['"',"\n"], ['\\"',''], $name);
    $entry = str_replace(['"',"\n"], ['\\"',''], $entry);
    $library = str_replace(['"',"\n"], ['\\"',''], $library);
    
    if (!str_starts_with($entry, '.'.DIRECTORY_SEPARATOR)) {
        die("The entry file path must be relative to the project, received: $entry.".PHP_EOL);
    }

    /** @var array<string> */
    $directories = !$library?[]:\preg_split('/,|;/', $library);

    foreach ($directories as $library) {
        if (!str_starts_with($library, '.'.DIRECTORY_SEPARATOR)) {
            die("All library directory paths must be relative to the project, received: $library.".PHP_EOL);
        }
    }

    $app = 'dist/app.phar';
    $start = 'dist/start';

    $dirnameStart = dirname($start);
    try {

        if(yield exists($dirnameStart)){
            yield deleteDirectoryRecursively($dirnameStart);
        }

        yield createDirectoryRecursively($dirnameStart);

        yield write($start,<<<PHP
        <?php
        use Amp\File\Filesystem;
        use Amp\Loop;
        use CatPaw\Amp\File\CatPawDriver;
        use CatPaw\Bootstrap;
        \$_ENV = [
            ...\$_ENV,
            ...getenv(),
        ];
        require 'vendor/autoload.php';

        if (isset(\$_ENV["CATPAW_FILE_DRIVER"]) && \$_ENV["CATPAW_FILE_DRIVER"]) {
            Loop::setState(\Amp\File\Driver::class, new Filesystem(new CatPawDriver));
        }
        Bootstrap::start(
            entry: "$entry",
            name: "$name",
            library: "$library",
            info: false,
            dieOnChange: false,
            resources: '',
        );
        PHP);

        if (yield exists($app)) {
            yield deleteFile($app);
        }

        if (yield exists($app . '.gz')) {
            yield deleteFile($app . '.gz');
        }
        
        $phar = new Phar($app);

        $phar->startBuffering();
        
        $directories = [];

        $phar->buildFromDirectory('.',$match);

        $phar->setStub(
            '#!/usr/bin/env php'
            .PHP_EOL
            .$phar->createDefaultStub($start)
        );

        $phar->setDefaultStub($start);

        $phar->stopBuffering();

        $phar->compressFiles(Phar::GZ);

        # Make the file executable
        chmod($app, 0770);

        yield deleteFile($start);

        echo "$app successfully created" . PHP_EOL;
    } catch (Exception $e) {
        die(((string)$e).PHP_EOL);
    }
}