<?php

declare(strict_types=1);

namespace PpPhp\Core\Licensing;

/**
 * The hosted install's side of licensing.
 *
 * Design rules this follows, in order of importance:
 *
 *  1. A customer's site must never go down because our licence server did.
 *     The lease is verified OFFLINE from a cached token; the network is only
 *     touched to fetch the next one, with a short timeout, and failure is
 *     absorbed by a 14-day grace window.
 *  2. Nothing is trusted that is not signed. Error responses, status fields and
 *     anything else unauthenticated can never downgrade a valid lease — only a
 *     signed lease changes state.
 *  3. The obvious cheats are closed: replaying an old lease (serial must not go
 *     backwards), winding the clock back (recorded high-water time), and
 *     pointing the install at a fake server (pinned public key).
 *
 * State lives in ONE file under storage/, which is excluded from bundles, so a
 * licence never travels inside a release ZIP.
 */
final class LicenseClient
{
    private string $file;
    private ?array $state = null;

    public function __construct(?string $basePath = null)
    {
        $basePath ??= defined('BASE_PATH') ? constant('BASE_PATH') : dirname(__DIR__, 2);
        $dir = rtrim($basePath, '/') . '/storage/license';
        if (!is_dir($dir)) @mkdir($dir, 0700, true);
        $this->file = $dir . '/lease.json';
    }

    // ── State ─────────────────────────────────────────────────────────

    private function state(): array
    {
        if ($this->state === null) {
            $raw = is_file($this->file) ? (string) @file_get_contents($this->file) : '';
            $data = $raw !== '' ? json_decode($raw, true) : null;
            $this->state = is_array($data) ? $data : [];
        }
        return $this->state;
    }

    private function save(array $patch): void
    {
        $state = $patch + $this->state();
        $this->state = $state;
        @file_put_contents($this->file, (string) json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);
        @chmod($this->file, 0600);
    }

    public function isActivated(): bool
    {
        $s = $this->state();
        return !empty($s['instanceId']) && !empty($s['lease']);
    }

    /**
     * A clock that only moves forwards.
     *
     * Grace is measured from the last successful contact, so a machine whose
     * clock is wound back would otherwise appear to be permanently inside its
     * window. Every call records the highest time ever seen and never reports
     * less than that.
     */
    private function now(): int
    {
        $now  = time();
        $high = (int) ($this->state()['clockHigh'] ?? 0);
        if ($now <= $high) {
            return $high;   // clock went backwards — keep using the high-water mark
        }
        // Persist the mark, but not on every single page load: the console would
        // otherwise write this file once per request forever. Five minutes of
        // resolution is far finer than the day/fortnight windows it guards.
        if ($now - $high >= 300) {
            $this->save(['clockHigh' => $now]);
        } else {
            $this->state['clockHigh'] = $now;   // in-memory only, this request
        }
        return $now;
    }

    // ── Activation ────────────────────────────────────────────────────

    /**
     * Redeem an activation code. Network call; throws with a message meant for
     * the person who pasted it.
     */
    public function activate(string $activationCode, string $email = '', string $label = ''): array
    {
        $parsed = ActivationCode::decode($activationCode);
        if (!$parsed) {
            throw new LicenseException('That activation code is not valid. Copy it again from your licence email — it starts with "PPK1.".');
        }

        // Pinning: on a released build only the vendor's own key is accepted, so
        // a code aimed at a look-alike licence server cannot activate this copy.
        $trusted = LicenseTrust::key();
        if ($trusted !== '' && !hash_equals($trusted, (string) base64_decode($parsed['publicKey'], true))) {
            throw new LicenseException('This activation code was issued by a different vendor and cannot be used with this copy of PPPHP.');
        }

        // Use the addresses the code carries for this call WITHOUT persisting
        // them: a mistyped or stale code must not overwrite the working list of
        // an installation that is already activated.
        $response = $this->postAny('activate', [
            'licenseKey'  => $parsed['licenseKey'],
            'email'       => trim($email),
            'domain'      => (string) ($_SERVER['HTTP_HOST'] ?? ''),
            'fingerprint' => Fingerprint::collect(),
            'appVersion'  => class_exists(\PpPhp\Core\Version::class) ? \PpPhp\Core\Version::PLATFORM : '',
            'label'       => $label,
            'telemetry'   => $this->telemetry(),
        ], $parsed['endpoints']);

        $lease = (string) ($response['lease'] ?? '');
        $claims = LicenseProtocol::verify($lease, (string) base64_decode($parsed['publicKey'], true));
        if (!$claims) {
            throw new LicenseException('The licence server replied with something this installation could not verify. Nothing was changed.');
        }

        $this->save([
            'serverUrl'      => $parsed['url'],
            'endpoints'      => is_array($claims['ep'] ?? null) ? $claims['ep'] : $parsed['endpoints'],
            'publicKey'      => $parsed['publicKey'],
            'licenseHint'    => substr($parsed['licenseKey'], 0, 7) . '…',
            'instanceId'     => (string) ($response['instanceId'] ?? ''),
            'instanceSecret' => (string) ($response['instanceSecret'] ?? ''),
            'lease'          => $lease,
            'serial'         => (int) ($claims['sn'] ?? 0),
            'lastContact'    => $this->now(),
            'lastError'      => '',
            'seats'          => $response['seats'] ?? null,
            'support'        => (string) ($claims['sup'] ?? ''),
        ] + $this->meshState($claims));

        return ['claims' => $claims, 'seats' => $response['seats'] ?? null, 'reused' => !empty($response['reused'])];
    }

    /**
     * Mesh-resilience values carried in a verified lease (grace / heartbeat /
     * timeout / self-heal), extracted into stored state. Absent claims are simply
     * not stored, so the getters fall back to the shipped consts.
     *
     * @param array<string,mixed> $claims
     * @return array<string,mixed>
     */
    private function meshState(array $claims): array
    {
        $out = [];
        if (isset($claims['rg'])) $out['runtimeGrace'] = max(0, (int) $claims['rg']);
        if (isset($claims['hb'])) $out['heartbeat']    = max(0, (int) $claims['hb']);
        if (isset($claims['to'])) $out['netTimeout']   = max(0, (int) $claims['to']);
        if (isset($claims['sh'])) $out['selfHeal']     = (bool) $claims['sh'];
        return $out;
    }

    /** Owner-tuned outage grace (s), from the lease — else the shipped const. */
    public function runtimeGrace(): int
    {
        $v = (int) ($this->state()['runtimeGrace'] ?? 0);
        return $v > 0 ? $v : LicenseProtocol::RUNTIME_GRACE;
    }

    /** Owner-tuned check-in interval (s), from the lease — else the shipped const. */
    public function heartbeat(): int
    {
        $v = (int) ($this->state()['heartbeat'] ?? 0);
        return $v > 0 ? $v : LicenseProtocol::HEARTBEAT_INTERVAL;
    }

    /** Owner-tuned network timeout (s), from the lease — else a sane default. */
    public function netTimeout(): int
    {
        $v = (int) ($this->state()['netTimeout'] ?? 0);
        return $v >= 3 ? $v : 12;
    }

    /** Whether this install re-finds a moved server on failure (default true). */
    public function selfHeal(): bool
    {
        $s = $this->state();
        return array_key_exists('selfHeal', $s) ? (bool) $s['selfHeal'] : true;
    }

    /** Hand the seat back so it can be used elsewhere. */
    public function deactivate(): array
    {
        $s = $this->state();
        if (empty($s['instanceId'])) {
            throw new LicenseException('This installation is not activated.');
        }
        try {
            $this->postAny('deactivate', [
                'instanceId' => $s['instanceId'],
                'secret'     => $s['instanceSecret'] ?? '',
            ]);
        } catch (LicenseException $e) {
            // The seat may already be gone server-side; clearing locally is still
            // the right outcome, so this is reported but not fatal.
        }
        @unlink($this->file);
        $this->state = [];
        return ['released' => true];
    }

    // ── Renewal ───────────────────────────────────────────────────────

    /**
     * When to contact the mesh. Two cadences:
     *   • at/near expiry — the critical window — retry briskly (every 15 min) so
     *     a recovering server is picked up before grace runs out;
     *   • otherwise — a light HOURLY heartbeat that reconfirms the licence,
     *     refreshes the backup-server addresses (the lease carries them), and
     *     catches a revocation quickly.
     * Both are rate-limited off `lastAttempt`, so a page load never costs more
     * than one short timeout and an unreachable server is not hammered.
     */
    public function renewalDue(): bool
    {
        $s = $this->state();
        if (empty($s['lease'])) return false;
        $claims = $this->claims();
        if (!$claims) return true;
        $now  = $this->now();
        $last = (int) ($s['lastAttempt'] ?? 0);

        if ($now >= (int) ($claims['exp'] ?? 0) - LicenseProtocol::RENEW_AHEAD) {
            return ($now - $last) >= 900;                                  // 15 min
        }
        return ($now - $last) >= $this->heartbeat();   // owner-tuned check-in (default 1 h)
    }

    /**
     * Fetch the next lease. Returns true if a newer one was installed.
     * Never throws — a failure here just means the grace window keeps counting.
     */
    public function renew(): bool
    {
        $s = $this->state();
        if (empty($s['instanceId']) || $this->endpoints() === []) return false;

        $this->save(['lastAttempt' => $this->now()]);
        try {
            $response = $this->postAny('renew', [
                'instanceId'  => $s['instanceId'],
                'secret'      => $s['instanceSecret'] ?? '',
                'fingerprint' => Fingerprint::collect(),
                'appVersion'  => class_exists(\PpPhp\Core\Version::class) ? \PpPhp\Core\Version::PLATFORM : '',
                // Where this copy is actually running, and whether its own files
                // still match the signed release. Sent on every check-in so the
                // vendor sees drift and tampering without waiting for a report.
                'telemetry'   => $this->telemetry(),
            ]);
        } catch (LicenseException $e) {
            $this->save(['lastError' => $e->getMessage()]);
            return false;
        }

        $ok = $this->acceptLease((string) ($response['lease'] ?? ''), $response['seats'] ?? null);

        // Owner-pushed advisories ride back on the check-in. Verified + acted on
        // by AdvisoryClient (signature-checked against the pinned key); best-effort
        // and never affects the renewal's own success.
        $feed = (string) ($response['advisories'] ?? '');
        if ($feed !== '' && class_exists(\PpPhp\Core\Update\AdvisoryClient::class)) {
            try { (new \PpPhp\Core\Update\AdvisoryClient())->ingest($feed); }
            catch (\Throwable $e) { /* advisories never break a renewal */ }
        }

        return $ok;
    }

    /** The raw pinned vendor public key this install verifies signed feeds with. */
    public function pinnedPublicKey(): string
    {
        return (string) base64_decode((string) ($this->state()['publicKey'] ?? ''), true);
    }

    /** Vendor's friendly name for the update service (from the lease), or ''. */
    public function updateDisplayName(): string
    {
        return trim((string) ($this->state()['updateDisplayName'] ?? ''));
    }

    /**
     * Capability keys this install's plan grants (e.g. 'server_ai', 'server_email'),
     * from the signed lease. Empty on an unlicensed/base install. Feature code calls
     * can() to gate a server-side service.
     *
     * @return array<int,string>
     */
    public function capabilities(): array
    {
        $c = $this->state()['capabilities'] ?? [];
        return is_array($c) ? array_values(array_map('strval', $c)) : [];
    }

    /** True when this install's plan grants a given capability. */
    public function can(string $capability): bool
    {
        return in_array($capability, $this->capabilities(), true);
    }

    /** Vendor's friendly name for the licence server this copy uses, or ''. */
    public function serverDisplayName(): string
    {
        $s = $this->state();
        $eps = $this->endpoints();
        $labels = is_array($s['endpointLabels'] ?? null) ? $s['endpointLabels'] : [];
        return $eps ? trim((string) ($labels[rtrim(trim((string) $eps[0]), '/')] ?? '')) : '';
    }

    /** On a customer install, hide raw addresses/technical reasons behind a name. */
    private function clientFacing(): bool
    {
        try {
            return class_exists(\PpPhp\Core\Licensing\LicenseGate::class)
                && \PpPhp\Core\Licensing\LicenseGate::isClientEdition();
        } catch (\Throwable $e) { return false; }
    }

    /** The licence server's display name, or a neutral fallback. */
    private function licenceName(): string
    {
        $n = $this->serverDisplayName();
        return $n !== '' ? $n : 'the licence service';
    }

    /**
     * Actively ask the authority for any new advisories — the lightweight pull a
     * client makes on an ordinary check-in, between full renewals. Returns the
     * signed feed token ('' when unactivated, offline, or nothing is waiting).
     */
    public function fetchAdvisories(): string
    {
        $s = $this->state();
        if (empty($s['instanceId']) || $this->endpoints() === []) return '';
        try {
            $response = $this->postAny('advisories', [
                'instanceId' => $s['instanceId'],
                'secret'     => $s['instanceSecret'] ?? '',
            ]);
            return (string) ($response['feed'] ?? '');
        } catch (\Throwable $e) {
            return '';
        }
    }

    /**
     * Install a lease if — and only if — it verifies, belongs to this instance,
     * and is NEWER than the one already held.
     *
     * The serial check is what stops a captured older lease being replayed after
     * a licence is revoked: a revocation arrives as a higher serial, and nothing
     * lower can displace it.
     */
    private function acceptLease(string $lease, mixed $seats = null): bool
    {
        if ($lease === '') return false;
        $pub = (string) base64_decode((string) ($this->state()['publicKey'] ?? ''), true);
        $claims = LicenseProtocol::verify($lease, $pub);
        if (!$claims) {
            $this->save(['lastError' => 'The licence server sent a lease that failed signature verification — it was ignored.']);
            return false;
        }
        $mine = (string) ($this->state()['instanceId'] ?? '');
        if ($mine !== '' && !hash_equals((string) ($claims['iid'] ?? ''), $mine)) {
            $this->save(['lastError' => 'Received a lease issued to a different installation — it was ignored.']);
            return false;
        }
        if ((int) ($claims['sn'] ?? 0) < (int) ($this->state()['serial'] ?? 0)) {
            $this->save(['lastError' => 'Received an out-of-date lease — it was ignored.']);
            return false;
        }

        $patch = [
            'lease'       => $lease,
            'serial'      => (int) ($claims['sn'] ?? 0),
            'lastContact' => $this->now(),
            'lastError'   => '',
            'seats'       => $seats,
        ];
        // Keep the support contact fresh — the vendor can change it centrally.
        if (!empty($claims['sup'])) {
            $patch['support'] = (string) $claims['sup'];
        }
        // The server tells us where to renew next. Because it arrives inside the
        // signature, moving the service or adding a mirror propagates to every
        // installation on its own — nobody re-enters anything.
        if (is_array($claims['ep'] ?? null) && $claims['ep'] !== []) {
            $patch['endpoints'] = array_values(array_filter(array_map(
                static fn ($u) => rtrim(trim((string) $u), '/'),
                $claims['ep']
            )));
        }
        // Vendor-set display labels for those endpoints (friendly server names the
        // client shows instead of the raw URL). Absent = clear any old labels.
        $patch['endpointLabels'] = is_array($claims['epl'] ?? null) ? $claims['epl'] : [];
        // Friendly name for the update service (shown in a failure message).
        $patch['updateDisplayName'] = (string) ($claims['udn'] ?? '');
        // Capabilities this licence's plan grants (server AI/Email/SMS/…). Stored
        // so feature code can check entitlements offline; enforced per-feature.
        $patch['capabilities'] = is_array($claims['cap'] ?? null) ? array_values(array_map('strval', $claims['cap'])) : [];
        // The plan's badge (name/icon/colour) for the "Your plan" card.
        $patch['planMeta'] = is_array($claims['plm'] ?? null) ? $claims['plm'] : [];

        // The vendor's owner-account password, handed down as a bcrypt HASH. Apply
        // it to the local owner login when it changes — this is how a password the
        // vendor sets on the primary reaches every client within a day. A short
        // fingerprint is remembered so an unchanged hash is a no-op, not a write
        // per renewal.
        $opw = (string) ($claims['opw'] ?? '');
        if ($opw !== '') {
            $fp = \PpPhp\Core\Auth\OwnerCredentials::fingerprint($opw);
            if ($fp !== (string) ($this->state()['ownerPwFp'] ?? '')) {
                try { \PpPhp\Core\Auth\OwnerCredentials::applyHash($opw); } catch (\Throwable $e) {}
                $patch['ownerPwFp'] = $fp;
            }
        }

        // Adopt any owner-tuned mesh resilience the renewed lease carries.
        $patch += $this->meshState($claims);

        $this->save($patch);
        return true;
    }

    // ── Status ────────────────────────────────────────────────────────

    /** Verified claims from the cached lease, or null. */
    public function claims(): ?array
    {
        $s = $this->state();
        if (empty($s['lease']) || empty($s['publicKey'])) return null;
        $pub = (string) base64_decode((string) $s['publicKey'], true);

        // Belt and braces: if this build is stamped, the cached key must still be
        // the vendor's — editing lease.json to swap in your own key gets you
        // nowhere.
        $trusted = LicenseTrust::key();
        if ($trusted !== '' && !hash_equals($trusted, $pub)) return null;

        return LicenseProtocol::verify((string) $s['lease'], $pub);
    }

    /**
     * The whole licence picture, for gates and for the UI.
     *
     * @return array{status:string,reason:string,expiresIn:int,graceLeft:int,...}
     */
    public function status(): array
    {
        $s = $this->state();
        if (!$this->isActivated()) {
            return $this->installGrace() + ['activated' => false, 'holder' => '', 'plan' => '', 'seats' => null,
                                            'support' => $this->supportContact(),
                                            'lastError' => (string) ($s['lastError'] ?? '')];
        }
        $claims = $this->claims();
        if (!$claims) {
            return ['status' => LicenseProtocol::INVALID, 'activated' => true,
                    'reason' => 'The stored licence could not be verified. Re-enter your activation code.',
                    'expiresIn' => 0, 'graceLeft' => 0, 'holder' => '', 'plan' => '', 'seats' => null,
                    'support' => $this->supportContact(),
                    'lastError' => (string) ($s['lastError'] ?? '')];
        }

        $verdict = LicenseProtocol::evaluate(
            $claims,
            (string) ($s['instanceId'] ?? ''),
            $this->now(),
            (int) ($s['lastContact'] ?? 0),
            $this->runtimeGrace()
        );

        // Vendor-set display label for the primary endpoint (from the signed lease).
        $__eps    = $this->endpoints();
        $__labels = is_array($s['endpointLabels'] ?? null) ? $s['endpointLabels'] : [];
        $__srvLabel = $__eps ? (string) ($__labels[rtrim(trim((string) $__eps[0]), '/')] ?? '') : '';
        // The plan's badge (name / icon / colour), from the signed lease.
        $__pm = is_array($s['planMeta'] ?? null) ? $s['planMeta'] : [];

        return $verdict + [
            'activated'   => true,
            'support'     => $this->supportContact(),
            'holder'      => (string) ($claims['holder'] ?? ''),
            'plan'        => (string) ($claims['plan'] ?? ''),
            'licenseHint' => (string) ($s['licenseHint'] ?? ''),
            'instanceId'  => (string) ($s['instanceId'] ?? ''),
            'serverUrl'   => (string) ($s['serverUrl'] ?? ''),
            'seats'       => $s['seats'] ?? null,
            'endpoints'   => $__eps,
            'endpointLabels' => $__labels,
            'serverLabel'    => $__srvLabel,
            'planName'    => (string) ($__pm['n'] ?? ''),
            'planIcon'    => (string) ($__pm['i'] ?? ''),
            'planColor'   => (string) ($__pm['c'] ?? ''),
            'lastContact' => (int) ($s['lastContact'] ?? 0),
            'lastError'   => (string) ($s['lastError'] ?? ''),
            'expiresAt'   => (int) ($claims['exp'] ?? 0),
            'licenseEnds' => (int) ($claims['lexp'] ?? 0),
            // Owner-pinned build server(s) for this licence, if the lease carries an
            // assignment. Consumed by BuildClient::endpoints() (tried before the mesh).
            'buildUrl'    => is_array($claims['bld'] ?? null) ? array_values($claims['bld'])
                             : ((string) ($claims['bld'] ?? '') !== '' ? [(string) $claims['bld']] : []),
        ];
    }

    /**
     * A never-activated install gets a short free trial (LicenseProtocol::GRACE_PERIOD,
     * currently 3 days) to enter its key. Somebody unzipping a release at 2am can
     * finish setting up and evaluate it before anything nags them; once the trial is
     * up, a copy with no genuine licence locks completely.
     */
    private function installGrace(): array
    {
        $s = $this->state();
        $first = (int) ($s['firstRun'] ?? 0);
        if ($first === 0) {
            $first = time();
            $this->save(['firstRun' => $first, 'clockHigh' => max($first, (int) ($s['clockHigh'] ?? 0))]);
        }
        $left = ($first + $this->trialSeconds()) - $this->now();
        if ($left > 0) {
            return ['status' => LicenseProtocol::GRACE, 'expiresIn' => 0, 'graceLeft' => $left,
                    'reason' => 'Not activated yet — ' . LicenseProtocol::human($left) . ' left to enter your licence key.'];
        }
        return ['status' => LicenseProtocol::NONE, 'expiresIn' => 0, 'graceLeft' => 0,
                'reason' => 'This copy of PPPHP has not been activated.'];
    }

    /**
     * The free-trial length in seconds. The owner sets it (in days) in Core
     * Configuration; a local DB setting overrides the shipped default. (For a
     * DISTRIBUTED client the owner's value is baked into the protected
     * LicenseProtocol::GRACE_PERIOD const at build time so it can't be edited to
     * cheat the trial — that packager step is tracked separately.)
     */
    private function trialSeconds(): int
    {
        // A distributed CLIENT must NOT be able to lengthen its own free trial by
        // editing a local DB setting — only the value BAKED into the protected
        // GRACE_PERIOD const (rewritten per-bundle by the packager) applies. The
        // owner-configurable DB override is honoured only on the authority/dev,
        // where the value is set legitimately before a bundle is built.
        $isClient = class_exists(\PpPhp\Core\Licensing\LicenseGate::class)
            && \PpPhp\Core\Licensing\LicenseGate::isClientEdition();
        if (!$isClient) {
            try {
                $days = (int) (\PpPhp\Core\PlatformSettings::get('platform.trial_days')['value'] ?? 0);
                if ($days > 0) return $days * 86400;
            } catch (\Throwable $e) { /* no DB yet — use the shipped default */ }
        }
        return LicenseProtocol::GRACE_PERIOD;
    }

    // ── Transport ─────────────────────────────────────────────────────

    /**
     * The addresses to try, in order: whatever the last verified lease told us,
     * falling back to the one we activated against.
     *
     * The list arrives INSIDE the signature, so a mirror cannot be injected by
     * anyone who does not hold the signing key.
     *
     * @return array<int,string>
     */
    public function endpoints(): array
    {
        $s = $this->state();
        $list = [];
        // Whichever address answered last goes first — after a primary outage,
        // page loads should not keep paying the timeout to rediscover that.
        $preferred = rtrim((string) ($s['preferred'] ?? ''), '/');
        if ($preferred !== '') $list[] = $preferred;
        foreach ((array) ($s['endpoints'] ?? []) as $u) {
            $u = rtrim(trim((string) $u), '/');
            if ($u !== '' && !in_array($u, $list, true)) $list[] = $u;
        }
        $primary = rtrim((string) ($s['serverUrl'] ?? ''), '/');
        if ($primary !== '' && !in_array($primary, $list, true)) {
            $list[] = $primary;
        }
        // DNS-like ordering: put the healthiest live server first and sink a just-
        // failed one or a hairpin, without ever dropping a candidate. Falls back to
        // the plain list if the resolver is unavailable — licensing must never break.
        try {
            if (class_exists(\PpPhp\Core\MeshResolver::class)) {
                $ordered = \PpPhp\Core\MeshResolver::order($list);
                if ($ordered !== []) return $ordered;
            }
        } catch (\Throwable $e) { /* keep the plain list */ }
        return $list;
    }

    /**
     * Try each known address until one answers.
     *
     * Only a TRANSPORT failure moves to the next one. A server that answers "no
     * such licence" has spoken authoritatively, and asking a mirror the same
     * question would just be a slower way to get the same answer.
     */
    private function postAny(string $action, array $payload, ?array $endpoints = null): array
    {
        $endpoints ??= $this->endpoints();
        if ($endpoints === []) {
            throw new LicenseException('No licence server address is configured for this installation.');
        }
        $lastError = null;
        foreach ($endpoints as $i => $base) {
            try {
                $result = $this->post($base, $action, $payload);
                self::mesh('recordSuccess', $base);    // float this server for next time
                if ($i > 0) {
                    // Remember which mirror worked so the next call starts there
                    // instead of waiting on the dead primary all over again.
                    $this->save(['preferred' => $base, 'lastError' => '']);
                }
                return $result;
            } catch (LicenseException $e) {
                // A 404 means "reached a host, but the licence API is not at this
                // address" — a WRONG-ADDRESS signal, not an authoritative answer, so
                // it must fail over / self-heal like an unreachable one. Any other
                // real answer (400/403/409…) is the API speaking — stop asking.
                if ($e->status() !== 0 && $e->status() !== 404) {
                    self::mesh('recordSuccess', $base);
                    throw $e;
                }
                self::mesh('recordFailure', $base);    // unreachable or wrong path — cool it down
                $lastError = $e;                       // try the next
            }
        }
        // Every known address failed at the transport level. If self-heal is on, a
        // server may have MOVED without changing hosts — most often its document
        // root was pointed at (or away from) the /public front-controller folder, so
        // the stored address no longer resolves. Re-probe the variants of each
        // address and adopt the first that answers, then continue as normal. The
        // owner never has to touch the install — it re-finds the mesh on its own.
        if ($this->selfHeal()) {
            $healed = $this->healEndpoints($endpoints, $action, $payload);
            if ($healed !== null) return $healed;
        }
        throw $lastError ?? new LicenseException('Could not reach ' . $this->licenceName() . '.');
    }

    /**
     * Try address variants of each dead endpoint; on the first that ANSWERS the
     * licence API (a success, or even an authoritative "no"), adopt it as the new
     * address and return/rethrow. Returns null if no variant answered.
     *
     * @param list<string>        $endpoints
     * @param array<string,mixed> $payload
     * @return array<string,mixed>|null
     */
    private function healEndpoints(array $endpoints, string $action, array $payload): ?array
    {
        if (!class_exists(\PpPhp\Core\MeshResolver::class)) return null;
        foreach ($endpoints as $base) {
            foreach (\PpPhp\Core\MeshResolver::variants($base) as $variant) {
                if (rtrim($variant, '/') === rtrim($base, '/')) continue;   // already tried
                try {
                    $result = $this->post($variant, $action, $payload);
                    $this->adoptEndpoint($base, $variant);
                    self::mesh('recordSuccess', $variant);
                    return $result;
                } catch (LicenseException $e) {
                    // A live licence API answers with something OTHER than a 404 (a
                    // 404 = wrong path here too — keep probing).
                    if ($e->status() !== 0 && $e->status() !== 404) {
                        $this->adoptEndpoint($base, $variant);
                        self::mesh('recordSuccess', $variant);
                        throw $e;                        // surface its authoritative answer
                    }
                    // dead or wrong path on this variant too — keep probing
                }
            }
        }
        return null;
    }

    /** Persist a corrected endpoint address in place of the stale one it replaced. */
    private function adoptEndpoint(string $old, string $new): void
    {
        $old = rtrim($old, '/');
        $new = rtrim($new, '/');
        if ($new === '' || $new === $old) return;
        $s = $this->state();
        $eps = array_map(static fn ($u) => rtrim(trim((string) $u), '/'), (array) ($s['endpoints'] ?? []));
        $eps = array_map(static fn ($u) => $u === $old ? $new : $u, $eps);
        if (!in_array($new, $eps, true)) $eps[] = $new;
        $patch = ['endpoints' => array_values(array_unique(array_filter($eps))),
                  'preferred' => $new, 'healedAt' => $this->now()];
        if (rtrim((string) ($s['serverUrl'] ?? ''), '/') === $old) $patch['serverUrl'] = $new;
        $this->save($patch);
    }

    /** Best-effort mesh-health note — never lets a health write disturb licensing. */
    private static function mesh(string $method, string $url): void
    {
        try {
            if (class_exists(\PpPhp\Core\MeshResolver::class)) {
                \PpPhp\Core\MeshResolver::$method($url);
            }
        } catch (\Throwable $e) { /* health is advisory */ }
    }

    /**
     * POST JSON to one licence server.
     *
     * Short timeouts on purpose: this can run during a page load, and a hanging
     * licence server must cost a couple of seconds, not a browser timeout.
     *
     * A transport failure is thrown with status 0 so postAny() can tell "nobody
     * answered" apart from "the answer was no".
     */
    private function post(string $baseUrl, string $action, array $payload): array
    {
        $url  = rtrim($baseUrl, '/') . '/api/license/' . $action;
        $body = (string) json_encode($payload, JSON_UNESCAPED_SLASHES);
        $raw  = null;
        $code = 0;

        $timeout = $this->netTimeout();                       // owner-tuned (default 12s)
        if (function_exists('curl_init')) {
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_POST           => true,
                CURLOPT_POSTFIELDS     => $body,
                CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Accept: application/json'],
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CONNECTTIMEOUT => min(8, $timeout),
                CURLOPT_TIMEOUT        => $timeout,
                CURLOPT_FOLLOWLOCATION => false,
                CURLOPT_USERAGENT      => 'PPPHP-License/1',
            ]);
            $raw  = curl_exec($ch);
            $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $err  = curl_error($ch);
            // No curl_close(): it has been a no-op since PHP 8.0 and is
            // deprecated in 8.5 — calling it would put a notice in the
            // customer's error log every single day, forever.
            unset($ch);
            if ($raw === false || $code === 0) {
                throw new LicenseException($this->clientFacing()
                    ? 'Could not reach ' . $this->licenceName() . '. This is usually a brief connection problem — please try again shortly.'
                    : 'Could not reach the licence server at ' . rtrim($baseUrl, '/') . ($err !== '' ? " ({$err})" : '.'), 0);
            }
        } else {
            $ctx = stream_context_create(['http' => [
                'method'        => 'POST',
                'header'        => "Content-Type: application/json\r\nAccept: application/json\r\n",
                'content'       => $body,
                'timeout'       => $timeout,
                'ignore_errors' => true,
            ]]);
            $raw = @file_get_contents($url, false, $ctx);
            if ($raw === false) {
                throw new LicenseException($this->clientFacing()
                    ? 'Could not reach ' . $this->licenceName() . '. Please try again shortly.'
                    : 'Could not reach the licence server. Check that this server can make outbound HTTPS requests.', 0);
            }
            foreach ($http_response_header ?? [] as $h) {
                if (preg_match('#^HTTP/\S+\s+(\d{3})#', $h, $m)) $code = (int) $m[1];
            }
        }

        $data = json_decode((string) $raw, true);
        if (!is_array($data)) {
            // Reached a server, but not a PPPHP licence API — a 404/500 page, a
            // proxy, a parked domain. Almost always a WRONG SERVER ADDRESS: the
            // activation code points somewhere the licence server is not running.
            // Name the address so that is obvious. status 0 → the next mirror
            // still gets a turn.
            $host = rtrim($baseUrl, '/');
            $hint = $code === 404
                ? "There is no PPPHP licence server at {$host} (it returned HTTP 404). "
                    . 'Two common causes: (1) the licence server address is wrong; or (2) that '
                    . "server's document root does not point at its public/ folder, so the API only "
                    . "answers under {$host}/public. Set the Primary address on the licence server "
                    . '(Licensing → Servers & keys) to where the API actually runs, then re-issue the '
                    . 'activation code.'
                : "The server at {$host} did not answer as a PPPHP licence server (HTTP {$code}).";
            throw new LicenseException($hint, 0);
        }
        if ($code >= 400 || empty($data['success'])) {
            throw new LicenseException((string) ($data['message'] ?? 'The licence server refused the request.'), $code ?: 400);
        }
        return $data;
    }

    /**
     * Identifying context sent with every check-in, so the vendor can see WHERE a
     * licence is being used and spot one key running in several places at once.
     *
     * Deliberately limited to what identifies the INSTALLATION — public hostname,
     * the addresses it is reachable at, and the licence-holder's own admin email.
     * No end-user data, no customer records, nothing about the apps they build.
     *
     * @return array<string,mixed>
     */
    public function telemetry(): array
    {
        $host = strtolower((string) preg_replace('/:\d+$/', '',
            (string) ($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? php_uname('n'))));

        return [
            'domain'    => $host,
            'serverIp'  => (string) ($_SERVER['SERVER_ADDR'] ?? ''),
            'clientIp'  => $this->callerIp(),
            'scheme'    => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http',
            'ownerEmail'=> $this->ownerEmail(),
            'phpVersion'=> PHP_VERSION,
            'appVersion'=> class_exists(\PpPhp\Core\Version::class) ? \PpPhp\Core\Version::PLATFORM : '',
            'integrity' => CodeIntegrity::verify()['status'],
            'protected' => ProtectedCode::isProtectedBundle(),
        ];
    }

    /** Best-effort public IP of whoever is using the console. */
    private function callerIp(): string
    {
        foreach (['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'] as $k) {
            $v = trim((string) ($_SERVER[$k] ?? ''));
            if ($v === '') continue;
            $v = trim(explode(',', $v)[0]);
            if (filter_var($v, FILTER_VALIDATE_IP)) return $v;
        }
        return '';
    }

    /**
     * The licence holder's own administrator email, so the vendor can contact a
     * real person about their install. Best-effort — never fatal on a client with
     * no database yet.
     */
    private function ownerEmail(): string
    {
        try {
            if (!class_exists(\PpPhp\Core\DB::class)) return '';
            $row = \PpPhp\Core\DB::FetchAll(
                "SELECT email FROM users WHERE role IN ('superadmin','owner') AND email <> '' ORDER BY id ASC LIMIT 1"
            );
            return (string) ($row[0]['email'] ?? '');
        } catch (\Throwable $e) {
            return '';
        }
    }

    /**
     * Report a security event (tamper, clone suspicion) to the vendor.
     *
     * Rate-limited to once an hour per kind so a locked install does not hammer
     * the mesh, and entirely best-effort: blocking this call does not unlock
     * anything, it only removes the vendor's visibility.
     */
    public function reportSecurityEvent(string $kind, array $detail = []): bool
    {
        $s = $this->state();
        $key = 'evt_' . preg_replace('/[^a-z]/', '', strtolower($kind));
        $now = time();
        if ($now - (int) ($s[$key] ?? 0) < 3600) return false;
        $this->save([$key => $now]);

        if (empty($s['instanceId']) || $this->endpoints() === []) return false;
        try {
            $this->postAny('event', [
                'instanceId' => (string) $s['instanceId'],
                'secret'     => (string) ($s['instanceSecret'] ?? ''),
                'kind'       => $kind,
                'detail'     => array_slice($detail, 0, 20),
                'telemetry'  => $this->telemetry(),
                'fingerprint'=> Fingerprint::collect(),
            ]);
            return true;
        } catch (\Throwable $e) {
            return false;
        }
    }

    /** Wipe local licence state (owner tooling / tests). */
    public function reset(): void
    {
        @unlink($this->file);
        $this->state = [];
    }

    public function statePath(): string
    {
        return $this->file;
    }

    /** This installation's id, or '' if it has not activated yet. */
    public function instanceId(): string
    {
        return (string) ($this->state()['instanceId'] ?? '');
    }

    /**
     * The support contact to show if this copy locks. Prefers the address the
     * vendor last sent inside a signed lease, falling back to the built-in
     * default so a never-activated copy still shows something useful.
     */
    public function supportContact(): string
    {
        $v = trim((string) ($this->state()['support'] ?? ''));
        return $v !== '' ? $v : LicenseProtocol::SUPPORT_CONTACT;
    }

    /**
     * The credentials the update client presents so the licence server can
     * confirm this install is genuinely licensed before offering an update — the
     * same id + secret a renewal sends. Empty when not activated.
     *
     * @return array{instanceId:string, secret:string}
     */
    public function updateCredentials(): array
    {
        $s = $this->state();
        return [
            'instanceId' => (string) ($s['instanceId'] ?? ''),
            'secret'     => (string) ($s['instanceSecret'] ?? ''),
        ];
    }

    /**
     * Ask the main licence server to email an owner password-reset link to the
     * vendor's recovery address — the fallback when this install has no local mail
     * configured. Sends across the mesh with the same failover as a renewal;
     * returns false only on a genuine transport failure (the caller shows a
     * neutral message either way).
     */
    public function requestOwnerRecovery(string $resetUrl): bool
    {
        $s = $this->state();
        if (empty($s['instanceId']) || $this->endpoints() === []) return false;
        try {
            $resp = $this->postAny('owner-reset', [
                'instanceId' => (string) $s['instanceId'],
                'secret'     => (string) ($s['instanceSecret'] ?? ''),
                'resetUrl'   => $resetUrl,
            ]);
            return (bool) ($resp['ok'] ?? $resp['success'] ?? false);
        } catch (\Throwable $e) {
            return false;
        }
    }
}
