import { describe, it, expect } from 'vitest';
import { Command } from 'commander';
import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { tmpdir } from 'node:os';
import { fileURLToPath } from 'node:url';
import {
  LEASE_ACTIVATION_CAPABILITY,
  LEASE_CAPABILITY_PROBE_COMMAND,
  defaultCapabilityProbe,
  defaultResolveCliEntry,
  defaultSupervisorProbe,
  leaseEnforcementActivatable,
  registerLeaseCapabilityProbe,
  type LeaseActivationCapability,
  type SupervisorProbeResult,
} from './lease-activation-probe.js';

/**
 * Red-first tests for issue #869 Point-1 C1 — leaseEnforcementActivatable().
 *
 * Root cause under test: #828 shipped the lease broker's ENFORCEMENT half
 * (hooks) and ACTIVATION half (execLeaseGatedRuntime + a running daemon.py
 * broker) on different channels, and they drifted — the published CLI
 * tarball lacked the activation half even though it existed in source. The
 * predicate here must say NO when either half of activation is unavailable,
 * and only YES when both are genuinely present — never based on "does the
 * source file exist", but on a real capability signal + real supervisor
 * detection.
 */

const compatibleCapability: LeaseActivationCapability = { ...LEASE_ACTIVATION_CAPABILITY };
const presentSupervisor: SupervisorProbeResult = {
  supervisorPresent: true,
  socketPath: '/run/user/1000/mosaic-lease/broker.sock',
};

describe('leaseEnforcementActivatable', () => {
  it('is false when the activation capability is absent (null)', () => {
    const result = leaseEnforcementActivatable({
      getCapability: () => null,
      probeSupervisor: () => presentSupervisor,
    });
    expect(result).toBe(false);
  });

  it('is false when the activation capability name does not match', () => {
    const result = leaseEnforcementActivatable({
      getCapability: () => ({
        name: 'some-other-capability',
        version: LEASE_ACTIVATION_CAPABILITY.version,
      }),
      probeSupervisor: () => presentSupervisor,
    });
    expect(result).toBe(false);
  });

  it('is false when the activation capability version is incompatible (stale/newer build)', () => {
    const result = leaseEnforcementActivatable({
      getCapability: () => ({
        name: LEASE_ACTIVATION_CAPABILITY.name,
        version: LEASE_ACTIVATION_CAPABILITY.version + 1,
      }),
      probeSupervisor: () => presentSupervisor,
    });
    expect(result).toBe(false);
  });

  it('is false when the supervisor artifacts (launcher/daemon) are not present', () => {
    const result = leaseEnforcementActivatable({
      getCapability: () => compatibleCapability,
      probeSupervisor: () => ({
        supervisorPresent: false,
        socketPath: presentSupervisor.socketPath,
      }),
    });
    expect(result).toBe(false);
  });

  it('is false when the supervisor socket path is not resolvable', () => {
    const result = leaseEnforcementActivatable({
      getCapability: () => compatibleCapability,
      probeSupervisor: () => ({ supervisorPresent: true, socketPath: null }),
    });
    expect(result).toBe(false);
  });

  it('is false when BOTH capability and supervisor are absent', () => {
    const result = leaseEnforcementActivatable({
      getCapability: () => null,
      probeSupervisor: () => ({ supervisorPresent: false, socketPath: null }),
    });
    expect(result).toBe(false);
  });

  it('is true when a compatible capability AND a resolvable supervisor are both present', () => {
    const result = leaseEnforcementActivatable({
      getCapability: () => compatibleCapability,
      probeSupervisor: () => presentSupervisor,
    });
    expect(result).toBe(true);
  });

  it('uses the real default probes when no deps are injected (does not throw)', () => {
    // No live broker / built CLI is guaranteed in a test environment, so this
    // only asserts the predicate degrades to a safe boolean rather than
    // throwing — the fail-closed behavior itself is covered by the injected
    // cases above.
    expect(() => leaseEnforcementActivatable()).not.toThrow();
    expect(typeof leaseEnforcementActivatable()).toBe('boolean');
  });
});

describe('defaultCapabilityProbe', () => {
  it('returns null (fail-closed) when no built CLI artifact is resolvable', () => {
    // Deterministic regardless of ambient host state (e.g. a host that has
    // already run `pnpm build`, which would otherwise make this pass or fail
    // depending on whether dist/cli.js happens to exist) — inject a resolver
    // pointing at a path that cannot exist, rather than relying on this
    // checkout being unbuilt. The probe must report "no capability" rather
    // than fabricate one from source-tree presence — this is the exact
    // distinction #828's version skew needed: source existing is not the
    // same as the published artifact advertising the capability.
    const result = defaultCapabilityProbe({
      resolveCliEntry: () => '/nonexistent/mosaic-lease-activation-probe-test/cli.js',
    });
    expect(result).toBeNull();
  });

  describe('positive path — injected resolver, isolated scratch dir (never the real dist/)', () => {
    // A prior version of this test staged the stub cli.js at the package's
    // REAL resolved dist/ path and relied on afterEach to clean up "only
    // what it created" — which meant a host with a real pre-built
    // dist/cli.js (ordinary `pnpm build && pnpm test`) would have its real
    // ~26KB compiled CLI silently overwritten by an 87-byte stub, with no
    // restoration of the original content. That is exactly the kind of
    // build-artifact corruption #869 exists to prevent. This version uses
    // dependency injection exclusively: defaultCapabilityProbe() is never
    // called with its default resolver here, so it can never touch the real
    // package dist/ at all — proven below by asserting that path's
    // existence is unchanged by the test.
    it('returns the real {name, version} capability from a stub cli.js in a temp dir, and leaves the real dist/ untouched', () => {
      const packageRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
      const realDistDir = join(packageRoot, 'dist');
      const realDistPreexisted = existsSync(realDistDir);

      const scratchDir = mkdtempSync(join(tmpdir(), 'mosaic-lease-capability-probe-'));
      try {
        const scratchCliPath = join(scratchDir, 'cli.js');
        // Minimal stand-in for the built CLI's hidden __lease-capability
        // subcommand — prints exactly what registerLeaseCapabilityProbe()
        // wires the real `mosaic __lease-capability` command to print.
        writeFileSync(
          scratchCliPath,
          `process.stdout.write(JSON.stringify(${JSON.stringify(LEASE_ACTIVATION_CAPABILITY)}));\n`,
        );

        const result = defaultCapabilityProbe({ resolveCliEntry: () => scratchCliPath });
        expect(result).toEqual(LEASE_ACTIVATION_CAPABILITY);

        // The real package dist/ must be byte-for-byte untouched: this test
        // never invokes the default resolver, so the path's mere existence
        // (created or not) must be unchanged by having run this test.
        expect(existsSync(realDistDir)).toBe(realDistPreexisted);
      } finally {
        rmSync(scratchDir, { recursive: true, force: true });
      }
    });
  });
});

describe('defaultResolveCliEntry', () => {
  it('resolves the bare "@mosaicstack/mosaic" specifier (the exported "." entry), never the non-exported "./package.json" subpath', () => {
    // Fully isolated from the real filesystem/package state (no dependency
    // on whether @mosaicstack/mosaic has been built on this host) via an
    // injected fake resolver that mirrors Node's real behavior: the "."
    // export resolves fine, but "./package.json" is NOT in package.json's
    // `exports` map, so real `require.resolve` throws
    // ERR_PACKAGE_PATH_NOT_EXPORTED for it. This is genuinely red-first
    // against the reviewer-found bug: the old implementation resolved the
    // "./package.json" subpath here, which this fake throws on — the new
    // implementation must resolve only the bare specifier.
    const requestedSpecifiers: string[] = [];
    const fakeResolve = (specifier: string): string => {
      requestedSpecifiers.push(specifier);
      if (specifier === '@mosaicstack/mosaic') return '/fake/pkg/dist/index.js';
      throw new Error(`ERR_PACKAGE_PATH_NOT_EXPORTED: ${specifier}`);
    };

    const result = defaultResolveCliEntry(fakeResolve);

    expect(result).toBe(join('/fake/pkg/dist', 'cli.js'));
    expect(requestedSpecifiers).toEqual(['@mosaicstack/mosaic']);
  });
});

describe('defaultSupervisorProbe', () => {
  it('returns a well-shaped result without starting or connecting to anything', () => {
    const result = defaultSupervisorProbe({});
    expect(typeof result.supervisorPresent).toBe('boolean');
    expect(result.socketPath === null || typeof result.socketPath === 'string').toBe(true);
  });

  it('resolves a socket path from an explicit MOSAIC_LEASE_BROKER_SOCKET override', () => {
    const result = defaultSupervisorProbe({ MOSAIC_LEASE_BROKER_SOCKET: '/tmp/explicit.sock' });
    expect(result.socketPath).toBe('/tmp/explicit.sock');
  });
});

describe('registerLeaseCapabilityProbe', () => {
  it('registers a hidden subcommand named __lease-capability', () => {
    const program = new Command();
    program.exitOverride();
    registerLeaseCapabilityProbe(program);

    const registered = program.commands.find((c) => c.name() === LEASE_CAPABILITY_PROBE_COMMAND);
    expect(registered).toBeDefined();
    // Commander exposes "hidden" only as help-output suppression (no public
    // getter) — assert the observable behavior instead of a private field.
    expect(program.helpInformation()).not.toContain(LEASE_CAPABILITY_PROBE_COMMAND);
  });

  it('prints the capability constant as JSON when invoked', () => {
    const program = new Command();
    program.exitOverride();
    registerLeaseCapabilityProbe(program);

    let written = '';
    const originalWrite = process.stdout.write.bind(process.stdout);
    process.stdout.write = ((chunk: string) => {
      written += chunk;
      return true;
    }) as typeof process.stdout.write;

    try {
      program.parse(['node', 'mosaic', LEASE_CAPABILITY_PROBE_COMMAND]);
    } finally {
      process.stdout.write = originalWrite;
    }

    expect(JSON.parse(written)).toEqual(LEASE_ACTIVATION_CAPABILITY);
  });
});
