<?php
declare(strict_types=1);
namespace PpPhp\Core\Designer\Generation;
use PpPhp\Core\Designer\Generation\Contracts\GeneratedApplication;use PpPhp\Core\Designer\Generation\Contracts\GeneratedPage;use PpPhp\Core\Designer\Shell\DesignerApplicationShellRuntime;
final class DesignerGenerationRuntime{private array $operations=[];
 public function generatePage(array $page):GeneratedPage{$g=(new DesignerPageGenerator())->generate($page);$this->record('generatePage',['pageId'=>$g->id(),'pageType'=>$g->pageType()]);return $g;}
 public function generateApplication(array $shell):GeneratedApplication{$pages=[];foreach((array)($shell['pages']??[]) as $p){if(is_array($p))$pages[]=$this->generatePage($p);}foreach((array)($shell['authPages']??[]) as $p){if(is_array($p))$pages[]=$this->generatePage($p);} $app=GeneratedApplication::create((string)($shell['appId']??'generated_app'),(string)($shell['title']??'Generated Application'),$pages,(array)($shell['assets']??[]),(array)($shell['routes']??[]),(new DesignerApplicationShellRuntime())->render($shell),['source'=>'designer-shell','generatedAt'=>date('c')]);$this->record('generateApplication',['applicationId'=>$app->applicationId(),'pages'=>count($pages)]);return $app;}
 public function generateCrudApplication(string $appId,string $title,array $tables):GeneratedApplication{return $this->generateApplication((new DesignerApplicationShellRuntime())->createCrudApplication($appId,$title,$tables));}
 public function writePlan(GeneratedApplication $app):array{$rows=[];foreach($app->pages() as $p){$rows[]=['type'=>'page','path'=>$p->path(),'bytes'=>strlen($p->toArray()['html']??'')];}$rows[]=['type'=>'shell','path'=>'generated/app-shell.php','bytes'=>strlen($app->toArray()['shell']??'')];$rows[]=['type'=>'manifest','path'=>'generated/manifest.json','bytes'=>strlen(json_encode($app->manifest()))];return $rows;}
 public function stats(GeneratedApplication $app):array{$s=$app->toArray()['summary'];return ['operations'=>count($this->operations),'generatedPages'=>$s['pages']??0,'dashboardPages'=>$s['dashboardPages']??0,'gridPages'=>$s['gridPages']??0,'formPages'=>$s['formPages']??0,'authPages'=>$s['authPages']??0,'routes'=>$s['routes']??0,'writePlan'=>count($this->writePlan($app)),'assets'=>$app->manifest()['assets']??0];}
 private function record(string $op,array $payload):void{$this->operations[]=['operation'=>$op,'payload'=>$payload,'createdAt'=>date('c')];}
}
