import * as fs from 'node:fs';
import * as path from 'node:path';

export interface ICreatePackageOptions {
  readonly packageName: string;
  readonly version?: string;
  readonly mount?: string;
  readonly componentType?: string;
  readonly runtimeEntry?: string;
}

export function createMatrixPackage(rootDir: string, options: ICreatePackageOptions): {
  readonly packageDir: string;
  readonly packageName: string;
  readonly version: string;
} {
  const version = options.version ?? '1.0.0';
  const componentType = options.componentType ?? 'SampleActor';
  const mount = options.mount ?? 'sample.actor';
  const runtimeEntry = options.runtimeEntry ?? 'src/index.ts';
  const packageDir = path.join(rootDir, options.packageName.replace(/^@/, '').replace('/', '-'));
  fs.mkdirSync(path.join(packageDir, 'src'), { recursive: true });

  fs.writeFileSync(
    path.join(packageDir, 'matrix.json'),
    JSON.stringify(
      {
        name: options.packageName,
        version,
        runtime: { language: 'typescript', entry: runtimeEntry },
        components: [
          {
            type: componentType,
            export: componentType,
            mount,
            autoStart: true,
          },
        ],
        permissions: { fsPolicy: 'none' },
      },
      null,
      2
    ),
    'utf8'
  );

  fs.writeFileSync(
    path.join(packageDir, 'package.json'),
    JSON.stringify(
      {
        name: options.packageName,
        version,
        type: 'module',
        main: 'src/index.ts',
      },
      null,
      2
    ),
    'utf8'
  );

  fs.writeFileSync(
    path.join(packageDir, 'src', 'index.ts'),
    `export class ${componentType} {}\n`,
    'utf8'
  );

  return {
    packageDir,
    packageName: options.packageName,
    version,
  };
}
