import { describe, it } from 'node:test';
import { strict as assert } from 'node:assert';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { actorElementCommand } from '../../src/commands/actor-element.js';
import { installOpenMatrixCoreStub } from '../support/installCoreStub.ts';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, '../../../../');

describe('FP-30 mx actor-element scaffold', () => {
  it('creates paired actor and element scaffold package', async () => {
    const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mx-actor-element-'));
    const outputDir = path.join(tmpRoot, 'weather-panel');

    try {
      const result = await actorElementCommand('weather-panel', {
        cwd: repoRoot,
        outputDir,
      });

      assert.equal(fs.existsSync(path.join(outputDir, 'matrix.json')), true);
      assert.equal(fs.existsSync(path.join(outputDir, 'src', `${result.actorClassName}.ts`)), true);
      assert.equal(fs.existsSync(path.join(outputDir, 'src', `${result.elementClassName}.ts`)), true);
      assert.equal(fs.existsSync(path.join(outputDir, 'examples', 'query-value.mxq')), true);
      assert.equal(fs.existsSync(path.join(outputDir, 'examples', 'render-element.mxq')), true);

      const manifest = JSON.parse(fs.readFileSync(path.join(outputDir, 'matrix.json'), 'utf8')) as {
        components: Array<{ mount?: string; type?: string }>;
      };
      assert.equal(manifest.components.length, 2);
      assert.equal(manifest.components.some((entry) => entry.mount === 'weather-panel.actor'), true);
      assert.equal(manifest.components.some((entry) => entry.mount === 'weather-panel.element'), true);

      installOpenMatrixCoreStub(outputDir);

      const compile = spawnSync(
        process.execPath,
        [
          path.resolve(repoRoot, 'node_modules/tsx/dist/cli.mjs'),
          path.join(outputDir, 'src', 'index.ts'),
        ],
        { cwd: outputDir, encoding: 'utf8' }
      );
      assert.equal(compile.status, 0, compile.stderr || '(no stderr)');
    } finally {
      fs.rmSync(tmpRoot, { recursive: true, force: true });
    }
  });
});
