<?php

namespace App\Services;

use Illuminate\Support\Facades\Process;

class LegGovDiscoveryService
{
    public function discover(): array
    {
        $apps = [];

        $files = glob('/etc/apache2/sites-enabled/*.conf') ?: [];

        foreach ($files as $file) {
            $content = @file_get_contents($file);

            if ($content === false) {
                continue;
            }

            preg_match_all(
                '/<VirtualHost\b[^>]*>(.*?)<\/VirtualHost>/is',
                $content,
                $blocks
            );

            foreach ($blocks[1] ?? [] as $block) {
                if (!preg_match(
                    '/^\s*DocumentRoot\s+["\']?([^"\'\s]+)["\']?/mi',
                    $block,
                    $rootMatch
                )) {
                    continue;
                }

                $documentRoot = rtrim($rootMatch[1], '/');

                if (!preg_match(
                    '#^(/var/www/leggov-[^/]+)/public$#',
                    $documentRoot,
                    $appMatch
                )) {
                    continue;
                }

                $path = $appMatch[1];

                if (
                    !is_dir($path) ||
                    !is_file($path.'/artisan') ||
                    !is_file($path.'/.env')
                ) {
                    continue;
                }

                $name = basename($path);

                if (
                    str_contains(strtolower($name), 'backup') ||
                    $name === 'leggov-test' ||
                    $name === 'leggov-central'
                ) {
                    continue;
                }

                preg_match(
                    '/^\s*ServerName\s+([^\s#]+)/mi',
                    $block,
                    $serverMatch
                );

                $domain = $serverMatch[1] ?? null;

                $env = $this->readEnv($path.'/.env');

                $database = $env['DB_DATABASE'] ?? null;

                $apps[$path] ??= [
                    'name' => $name,
                    'path' => $path,
                    'database' => $database,
                    'domains' => [],
                ];

                if ($domain && !in_array($domain, $apps[$path]['domains'], true)) {
                    $apps[$path]['domains'][] = $domain;
                }
            }
        }

        ksort($apps);

        return array_values($apps);
    }

    private function readEnv(string $file): array
    {
        $result = [];

        foreach (@file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) {
            $line = trim($line);

            if ($line === '' || str_starts_with($line, '#') || !str_contains($line, '=')) {
                continue;
            }

            [$key, $value] = explode('=', $line, 2);

            $result[trim($key)] = trim(trim($value), "\"'");
        }

        return $result;
    }
}
