<?php
$settingsFile = realpath(dirname(__DIR__) . '/..') . DIRECTORY_SEPARATOR . 'settings.json';
$raw = file_get_contents($settingsFile);
$j = json_decode($raw, true);
if (!is_array($j)) {
    fwrite(STDERR, "Invalid settings.json\n");
    exit(1);
}
$icon = 'arquitect-app/icon.png';
$app = [
    'id' => 'sketchia-system',
    'title' => 'SkechIA',
    'icon' => $icon,
    'description' => 'Dibujo y diseño con capas e IA',
    'category' => 'Sistema',
    'link' => 'arquitect-app/index.html',
    'linkTarget' => 'window',
    'lastAction' => 'link',
    'showInGrid' => true,
    'isSystemApp' => true,
    'isPinned' => true,
];
$apps = $j['apps'] ?? [];
foreach ($apps as $a) {
    if (isset($a['id']) && ($a['id'] === 'sketchia-system' || $a['id'] === 'arquitect-studio-app')) {
        echo "Already registered.\n";
        exit(0);
    }
}
$appsList = $j['apps'] ?? [];
$explorerIdx = -1;
foreach ($appsList as $i => $a) {
    if (isset($a['id']) && $a['id'] === 'file-explorer-system') {
        $explorerIdx = (int) $i;
        break;
    }
}
if ($explorerIdx >= 0) {
    array_splice($appsList, $explorerIdx + 1, 0, [$app]);
} else {
    array_unshift($appsList, $app);
}
$j['apps'] = $appsList;

$pinned = $j['pinnedApps'] ?? [];
$skLink = 'arquitect-app/index.html';
$pinDup = false;
foreach ($pinned as $p) {
    $lk = isset($p['link']) ? str_replace('\\', '/', (string) $p['link']) : '';
    if ($lk === $skLink || substr($lk, -strlen($skLink)) === $skLink) {
        $pinDup = true;
        break;
    }
}
if (!$pinDup) {
    $pinEntry = ['title' => 'SkechIA', 'link' => $skLink, 'icon' => $icon];
    $exPin = -1;
    foreach ($pinned as $pi => $p) {
        if (($p['title'] ?? '') === 'Explorador' && ($p['link'] ?? '') === '#') {
            $exPin = (int) $pi;
            break;
        }
    }
    if ($exPin >= 0) {
        array_splice($pinned, $exPin + 1, 0, [$pinEntry]);
    } else {
        array_unshift($pinned, $pinEntry);
    }
    $j['pinnedApps'] = $pinned;
}

$out = file_put_contents($settingsFile, json_encode($j, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
if ($out === false) {
    fwrite(STDERR, "No se pudo escribir settings.json (permisos). Añade la app manualmente al array apps.\n");
    exit(1);
}
echo "SkechIA added to escritorio.\n";
