<?php

declare(strict_types=1);

require_once __DIR__ . '/CapabilityCatalog.php';
require_once __DIR__ . '/EntitlementSnapshot.php';
require_once __DIR__ . '/LicenseTier.php';

final class MyronDowngradeCompatibilityReport
{
    /**
     * @param list<string> $removedCapabilities
     * @param list<string> $affectedPackages
     */
    public function __construct(
        private readonly string $currentTier,
        private readonly string $targetTier,
        private readonly array $removedCapabilities,
        private readonly array $affectedPackages,
    ) {
    }

    public static function build(MyronEntitlementSnapshot $currentSnapshot, string $targetTier): self
    {
        $targetTier = MyronLicenseTier::normalize($targetTier);
        $removedCapabilities = [];
        $affectedPackages = [];
        $definitions = MyronCapabilityCatalog::definitions();
        foreach ($currentSnapshot->capabilities as $capability => $enabled) {
            if ($enabled !== true || MyronCapabilityCatalog::allows($targetTier, $capability)) {
                continue;
            }

            $removedCapabilities[] = $capability;
            $package = (string) ($definitions[$capability]['package'] ?? '');
            if ($package !== '') {
                $affectedPackages[$package] = true;
            }
        }

        sort($removedCapabilities);
        $affectedPackages = array_keys($affectedPackages);
        sort($affectedPackages);

        return new self($currentSnapshot->plan, $targetTier, $removedCapabilities, $affectedPackages);
    }

    public function isDowngrade(): bool
    {
        return MyronLicenseTier::rank($this->targetTier) < MyronLicenseTier::rank($this->currentTier);
    }

    public function requiresBackupAcknowledgement(): bool
    {
        return $this->isDowngrade() && $this->removedCapabilities !== [];
    }

    /**
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'currentTier' => $this->currentTier,
            'targetTier' => $this->targetTier,
            'isDowngrade' => $this->isDowngrade(),
            'requiresBackupAcknowledgement' => $this->requiresBackupAcknowledgement(),
            'removedCapabilities' => $this->removedCapabilities,
            'affectedPackages' => $this->affectedPackages,
            'dataPreservation' => 'Feature-created customer data must remain preserved and exportable; remediation removes code/package access, not customer data.',
        ];
    }
}
