<?php

namespace Lucent\Http\Controller;

use App\Http\Controllers\Controller;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Artisan;
use Lucent\Channel\ChannelService;
use Lucent\Svelte\Svelte;
use function Lucent\Response\ok;

class BuildController extends Controller
{
    public function __construct(
        public readonly Svelte         $svelte,
        public readonly ChannelService $channelService,
    )
    {
    }

    public function build()
    {

        $buildLogFile = storage_path("lucent/build.log");
        if(file_exists($buildLogFile)){
            unlink($buildLogFile);
        }

        exec("cd " . base_path() . " && php8.2 artisan {$this->channelService->channel->generateCommand} > " . $buildLogFile . " 2>&1 & echo $!", $op);
        $pid = (int)$op[0];
        return redirect($this->channelService->channel->lucentUrl . "/build-report");
    }

    public function report(): View
    {

        return $this->svelte->render(
            layout: "channel",
            view: "buildReport",
            title: "Build Report",
        );
    }

    public function reportSource()
    {
        return response()->stream(function () {
            while (true) {
//                sleep(1); // 50ms
                $data["date"] = date("Y-m-d H:i:s");
                $data["logs"] = file_get_contents(storage_path("lucent/build.log"));
//                $lines = explode("\n",$data["logs"]);

                echo 'data: ' .json_encode($data);
                echo "\n\n";

                ob_flush();
                flush();

                if(str_contains($data["logs"],"Finito")){
                    break;
                }

                if(str_contains($data["logs"],"Exception")){
                    break;
                }

                // Break the loop if the client aborted the connection (closed the page)
                if (connection_aborted()) {
                    break;
                }
                sleep(1); // 50ms
            }
        }, 200, [
            'Cache-Control' => 'no-cache',
            'X-Accel-Buffering' => 'no',
            'Content-Type' => 'text/event-stream',
        ]);
    }


}
