#!/usr/bin/env php
<?php
declare(strict_types=1);
require __DIR__.'/bootstrap.php';
$command=$argv[1]??'help';
try {
    if(in_array($command,['cms:setup-key','cms:prepare','cms:install','cms:upgrade','cms:status','cms:password'],true)) { DL\Cms\Console::run($command,$argv);exit; }
    if($command==='doctor') {
        $dsn=DL\Env::get('CMS_DB_DSN','sqlite:'.DL_ROOT.'/storage/cms.sqlite');
        $driver=str_starts_with($dsn,'mysql:')?'mysql':(str_starts_with($dsn,'sqlite:')?'sqlite':'unsupported');
        $checks=['PHP >= 8.2'=>version_compare(PHP_VERSION,'8.2.0','>='),'JSON'=>extension_loaded('json'),'Sessions'=>extension_loaded('session'),'fileinfo'=>extension_loaded('fileinfo'),'Configured PDO driver'=>class_exists(PDO::class)&&in_array($driver,PDO::getAvailableDrivers(),true),'Private storage writable'=>is_writable(DL_ROOT.'/storage'),'Media storage writable'=>is_writable(DL_ROOT.'/storage/media'),'Cache writable'=>is_writable(DL_ROOT.'/storage/cache')];
        foreach($checks as $name=>$ok)echo ($ok?'[OK] ':'[FAIL] ').$name.PHP_EOL;
        echo '[INFO] Theme ZIP support: '.(extension_loaded('zip')?'available':'optional extension not installed').PHP_EOL;
        echo "[INFO] TLS, web-root isolation and hosting permissions require operator verification.\n";
        exit(in_array(false,$checks,true)?1:0);
    }
    if($command==='routes') {echo json_encode((require DL_ROOT.'/app/routes.php')->manifest(),JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES).PHP_EOL;exit;}
    if($command==='help') {echo 'DL CMS '.DL\Cms\Release::VERSION."\n\nphp dl doctor             Check hosting prerequisites\nphp dl cms:setup-key      Create private ownership key (no database DDL)\nphp dl cms:prepare        Alias for cms:setup-key\nphp dl cms:status         Report non-secret installation status\nphp dl cms:upgrade        Apply versioned schema upgrades\nphp dl cms:install        Private operator install (JSON on stdin)\nphp dl cms:password EMAIL Private operator recovery (exact bytes on stdin)\nphp dl routes             Show CMS routes\n\nSee README.md and docs/cms-user-guide.md.\n";exit;}
    throw new InvalidArgumentException('Unknown command. Run php dl help.');
} catch(Throwable $error) {
    fwrite(STDERR,'[DL] '.($error instanceof PDOException?'Database operation failed; check private configuration and schema.':$error->getMessage()).PHP_EOL);exit(1);
}
