#!/usr/bin/env php
<?php

include $_composer_autoload_path ?? __DIR__ . '/../vendor/autoload.php';

echo "ℹ️ APIlite files\n\n";

$project_root = findProjectRoot(__DIR__);

if (!$project_root) {
	echo "⛔ Project root not found\n";
	exit(1);
}
$composer_arr = json_decode(file_get_contents($project_root . '/composer.json'), true);

echo "Project root: {$project_root}\n";
$source_dirs = array_values($composer_arr['autoload']['psr-4']);
foreach ($source_dirs as $index => $source_dir) {
	echo "➡️ [$index]: $project_root/$source_dir\n";
}
$selected = readline("❔ Select source dir [default: 0]: ");
$selected = empty($selected) ? 0 : $selected;
if (!isset($source_dirs[$selected])) {
	echo "⛔ Invalid selection\n";
	exit(2);
}
$source_dir = $project_root . '/' . $source_dirs[$selected];
$source_dir = rtrim($source_dir, '/') . '/';
$namespaces = array_keys($composer_arr['autoload']['psr-4']);
$namespace = $namespaces[$selected];
echo "✔️ Source dir: {$source_dir} with namespace: {$namespace}\n";

// Copy files
echo "ℹ️ Copy files\n";

copyFile($source_dir . 'API.php', '<' . '?php

namespace ' . rtrim($namespace, '\\') . ';

use TPsoft\APIlite\APIlite;

class API extends APIlite {

}
');

copyFile($project_root . '/scripts/buildTypeScript.php', '<' . '?php

require __DIR__ . \'/../vendor/autoload.php\';

ob_start();

$backend_api = new TPsoft\BugreportBackend\API(\'typescript\', \'import.meta.env.VITE_BACKENDAPI_URL\', \'backend\');

$output = ob_get_contents();
ob_end_clean();

$ts_path = realpath(__DIR__ . \'/../../frontend/src\').\'/backend.ts\';
$suc = file_put_contents($ts_path, $output);
if ($suc === false) {
	echo "✗ TypeScript store into file failed\n";
	exit(2);
}

echo "✓ TypeScript backend script created\n";
');

copyFile($project_root . '/public/API.php', '<' . '?php

require_once __DIR__.\'/../src/API.php\';
new \\' . $namespace . 'API();
');

// Change composer.json
if (!isset($composer_arr['scripts']['build'])) {
	$composer_arr['scripts']['build'] = 'php scripts/buildTypeScript.php';
}

$composer_json = json_encode($composer_arr, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$composer_json = preg_replace_callback(
	'/^( +)/m',
	fn($m) => str_repeat("\t", intdiv(strlen($m[1]), 4)),
	$composer_json
);
$suc = file_put_contents($project_root . '/composer.json', $composer_json);
if ($suc) {
	echo "✅ File changed: $project_root/composer.json\n";
} else {
	echo "🔴 Failed to change file: $project_root/composer.json\n";
}


/**
 * Functions
 */
function findProjectRoot(string $startDir): ?string
{
	$dir = realpath($startDir);
	if (!$dir) return null;
	while ($dir && $dir !== dirname($dir)) {
		if (is_file($dir . '/vendor/autoload.php')) {
			return $dir;
		}
		$dir = dirname($dir);
	}
	return null;
}

function copyFile(string $destination, string $content): bool
{
	$dir = dirname($destination);
	if (!file_exists($dir)) {
		mkdir($dir, 0777, true);
	}
	if (file_exists($destination)) {
		echo "⚠️ File already exists: $destination\n";
		$confirm = readline("❔ Overwrite? (y - yes, other - no): ");
		if ($confirm != 'y') {
			return false;
		}
	}
	$suc = file_put_contents($destination, $content) !== false;
	if ($suc) {
		echo "✅ File created: $destination\n";
	} else {
		echo "🔴 Failed to create file: $destination\n";
	}
	return $suc;
}
