<?php

namespace App\Services;
			
use App\Models\SystemUpdate;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use RuntimeException;
use ZipArchive;

class SystemUpdateService
{
    public function inspect(string $zipPath): array
    {
        $zip = new ZipArchive();
        if ($zip->open($zipPath) !== true) {
            throw new RuntimeException('The uploaded ZIP file could not be opened.');
        }

        try {
            $manifestJson = $zip->getFromName('manifest.json');
            if ($manifestJson === false) {
                throw new RuntimeException('manifest.json is required at the root of the update package.');
            }

            $manifest = json_decode($manifestJson, true);
            if (!is_array($manifest)) {
                throw new RuntimeException('manifest.json is not valid JSON.');
            }

            foreach (['product', 'version', 'files', 'sha256'] as $key) {
                if (!array_key_exists($key, $manifest)) {
                    throw new RuntimeException("manifest.json is missing: {$key}");
                }
            }

            if (($manifest['product'] ?? '') !== config('prime-next.product')) {
                throw new RuntimeException('This update package belongs to a different product.');
            }

            if (!preg_match('/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/', (string) $manifest['version'])) {
                throw new RuntimeException('The package version must use semantic version format, for example 1.2.0.');
            }

            $current = $this->currentVersion();
            if (version_compare($manifest['version'], $current, '<=')) {
                throw new RuntimeException("Package version {$manifest['version']} is not newer than the current version {$current}.");
            }

            $files = $manifest['files'];
            if (!is_array($files) || !is_array($manifest['sha256'])) {
                throw new RuntimeException('manifest.json files and sha256 must be arrays.');
            }

            $zipNames = [];
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $name = $zip->getNameIndex($i);
                if ($name !== false) {
                    $zipNames[] = $name;
                    if (!$this->safeRelativePath($name)) {
                        throw new RuntimeException("Unsafe path detected in package: {$name}");
                    }
                }
            }

            $declared = [];
            foreach ($files as $path) {
                if (!is_string($path) || !$this->safeRelativePath($path) || str_starts_with($path, 'manifest.json')) {
                    throw new RuntimeException('The package contains an invalid declared file path.');
                }
                $this->assertAllowedPath($path);
                $declared[] = $path;
                $content = $zip->getFromName('files/' . $path);
                if ($content === false) {
                    throw new RuntimeException("Declared file is missing from package: {$path}");
                }
                if (empty($manifest['sha256'][$path])) {
                    throw new RuntimeException("SHA-256 hash is missing for {$path}.");
                }
                $actualHash = hash('sha256', $content);
                if (!hash_equals(strtolower((string) $manifest['sha256'][$path]), $actualHash)) {
                    throw new RuntimeException("SHA-256 validation failed for {$path}.");
                }
            }

            $packageFiles = array_values(array_filter($zipNames, fn ($n) => $n !== 'manifest.json' && !str_ends_with($n, '/')));
            foreach ($packageFiles as $name) {
                if (!str_starts_with($name, 'files/')) {
                    throw new RuntimeException("Unexpected package entry: {$name}");
                }
                $path = substr($name, 6);
                $this->assertAllowedPath($path);
                if (!in_array($path, $declared, true)) {
                    throw new RuntimeException("Package file is not declared in manifest: {$path}");
                }
            }

            return [
                'manifest' => $manifest,
                'current_version' => $current,
                'file_count' => count($declared),
                'migration_count' => count(array_filter($declared, fn ($p) => str_starts_with($p, 'database/migrations/'))),
            ];
        } finally {
            $zip->close();
        }
    }

    public function install(string $zipPath, int $userId): SystemUpdate
    {
        $inspection = $this->inspect($zipPath);
        $manifest = $inspection['manifest'];
        $version = $manifest['version'];
        $packageName = $manifest['package_name'] ?? basename($zipPath);

        $record = SystemUpdate::create([
            'version' => $version,
            'package_name' => $packageName,
            'release_type' => $manifest['release_type'] ?? 'feature',
            'description' => $manifest['description'] ?? null,
            'manifest' => $manifest,
            'status' => 'installing',
            'installed_by' => $userId,
        ]);

        $stamp = now()->format('Ymd_His') . '_v' . $version;
        $backupRelative = config('prime-next.backup_directory') . '/' . $stamp;
        $backupAbsolute = Storage::disk(config('prime-next.update_disk'))->path($backupRelative);
        File::ensureDirectoryExists($backupAbsolute, 0750, true);

        $staging = Storage::disk(config('prime-next.update_disk'))->path(config('prime-next.update_directory') . '/staging/' . $stamp);
        File::ensureDirectoryExists($staging, 0750, true);

        $maintenanceEnabled = false;

        try {
            $this->extractPackage($zipPath, $staging);
            $this->backupFiles($manifest['files'], $backupAbsolute);
            $this->backupManifest($manifest['files'], $backupAbsolute . '/manifest.json');
            $this->backupDatabase($backupAbsolute . '/database.sql');

            Artisan::call('down', ['--render' => 'errors::503']);
            $maintenanceEnabled = true;

            foreach ($manifest['files'] as $path) {
                $source = $staging . '/files/' . $path;
                $target = base_path($path);
                File::ensureDirectoryExists(dirname($target), 0750, true);
                File::copy($source, $target);
            }

            Artisan::call('migrate', ['--force' => true]);
            Artisan::call('optimize:clear');

            $record->update([
                'status' => 'installed',
                'backup_path' => $backupRelative,
                'installed_at' => now(),
            ]);

            if ($maintenanceEnabled) {
                Artisan::call('up');
            }

            File::deleteDirectory($staging);
            return $record->fresh();
        } catch (\Throwable $e) {
            try {
                $this->restoreFiles($backupAbsolute . '/files');
                $this->removeNewFiles($backupAbsolute . '/manifest.json');
                $this->restoreDatabase($backupAbsolute . '/database.sql');
                Artisan::call('optimize:clear');
            } catch (\Throwable $rollbackError) {
                $e = new RuntimeException($e->getMessage() . ' Rollback also reported: ' . $rollbackError->getMessage(), 0, $e);
            }

            if ($maintenanceEnabled) {
                Artisan::call('up');
            }

            $record->update([
                'status' => 'failed',
                'backup_path' => $backupRelative,
                'error_message' => mb_substr($e->getMessage(), 0, 5000),
            ]);

            throw $e;
        } finally {
            @unlink($zipPath);
            File::deleteDirectory($staging);
        }
    }

    public function currentVersion(): string
    {
        $latest = SystemUpdate::where('status', 'installed')->orderByDesc('id')->value('version');
        return $latest ?: config('prime-next.version', '1.0.0');
    }

    private function extractPackage(string $zipPath, string $destination): void
    {
        $zip = new ZipArchive();
        if ($zip->open($zipPath) !== true) {
            throw new RuntimeException('Unable to open update package.');
        }
        try {
            if (!$zip->extractTo($destination)) {
                throw new RuntimeException('Unable to extract update package to staging area.');
            }
        } finally {
            $zip->close();
        }
    }

    private function backupManifest(array $paths, string $path): void
    {
        File::put($path, json_encode($paths, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    }

    private function backupFiles(array $paths, string $backupAbsolute): void
    {
        $filesDir = $backupAbsolute . '/files';
        File::ensureDirectoryExists($filesDir, 0750, true);
        foreach ($paths as $path) {
            $source = base_path($path);
            if (File::exists($source) && File::isFile($source)) {
                $target = $filesDir . '/' . $path;
                File::ensureDirectoryExists(dirname($target), 0750, true);
                File::copy($source, $target);
            }
        }
    }

    private function removeNewFiles(string $manifestPath): void
    {
        if (!File::exists($manifestPath)) {
            return;
        }
        $paths = json_decode(File::get($manifestPath), true) ?: [];
        $filesDir = dirname($manifestPath) . '/files';
        foreach ($paths as $path) {
            $backupPath = $filesDir . '/' . $path;
            if (!File::exists($backupPath)) {
                $target = base_path($path);
                if (File::exists($target) && File::isFile($target)) {
                    File::delete($target);
                }
            }
        }
    }

    private function restoreFiles(string $filesDir): void
    {
        if (!File::isDirectory($filesDir)) {
            return;
        }
        foreach (File::allFiles($filesDir) as $file) {
            $relative = ltrim(str_replace($filesDir, '', $file->getPathname()), DIRECTORY_SEPARATOR);
            $target = base_path($relative);
            File::ensureDirectoryExists(dirname($target), 0750, true);
            File::copy($file->getPathname(), $target);
        }
    }

    private function backupDatabase(string $path): void
    {
        $pdo = DB::connection()->getPdo();
        $database = DB::getDatabaseName();
        $fh = fopen($path, 'wb');
        if (!$fh) {
            throw new RuntimeException('Unable to create database backup.');
        }
        fwrite($fh, "-- Prime Next database backup\n-- Database: {$database}\n-- Created: " . now()->toDateTimeString() . "\n\nSET FOREIGN_KEY_CHECKS=0;\n\n");
        $tables = DB::select('SHOW TABLES');
        $key = 'Tables_in_' . $database;
        foreach ($tables as $row) {
            $table = $row->{$key} ?? array_values((array) $row)[0] ?? null;
            if (!$table) continue;
            $quoted = '`' . str_replace('`', '``', $table) . '`';
            $create = DB::selectOne("SHOW CREATE TABLE {$quoted}");
            $createSql = $create->{'Create Table'} ?? array_values((array) $create)[1] ?? null;
            if ($createSql) {
                fwrite($fh, "DROP TABLE IF EXISTS {$quoted};\n{$createSql};\n\n");
            }
            $rows = DB::table($table)->get();
            foreach ($rows as $item) {
                $values = [];
                foreach ((array) $item as $value) {
                    $values[] = $value === null ? 'NULL' : $pdo->quote((string) $value);
                }
                fwrite($fh, "INSERT INTO {$quoted} VALUES (" . implode(',', $values) . ");\n");
            }
            fwrite($fh, "\n");
        }
        fwrite($fh, "SET FOREIGN_KEY_CHECKS=1;\n");
        fclose($fh);
    }

    private function restoreDatabase(string $path): void
    {
        if (!File::exists($path)) {
            return;
        }
        $sql = File::get($path);
        DB::unprepared($sql);
    }

    private function safeRelativePath(string $path): bool
    {
        return $path !== '' && !str_contains($path, "\0") && !str_starts_with($path, '/') && !preg_match('/^[A-Za-z]:[\\\/]/', $path) && !preg_match('#(^|/|\\\\)\.\.?(/|\\\\|$)#', $path);
    }

    private function assertAllowedPath(string $path): void
    {
        foreach (config('prime-next.blocked_paths', []) as $blocked) {            if ($this->patternMatches($path, $blocked)) {
                throw new RuntimeException("Blocked path in update package: {$path}");
            }
        }
        foreach (config('prime-next.allowed_roots', []) as $root) {
            if ($path === $root || str_starts_with($path, $root)) {
                return;
            }
        }
        throw new RuntimeException("Path is outside the allowed update directories: {$path}");
    }

    private function patternMatches(string $path, string $pattern): bool
    {
        if (str_ends_with($pattern, '*')) {
            return str_starts_with($path, rtrim($pattern, '*'));
        }
        if (str_ends_with($pattern, '/')) {
            return str_starts_with($path, $pattern);
        }
        return $path === $pattern;
    }
}
