import * as path from 'path';
import {
  buildSkillRuntimeEnv,
  mergeSkillProcessEnv,
} from '../src/modules/netaclaw/service/skill_runtime_env.js';

describe('buildSkillRuntimeEnv', () => {
  it('injects dataDir, workspace root and upload root for vehicle damage inspection', () => {
    const dataDir = path.resolve('C:\\RZYX_AI_DATA');
    const uploadRoot = path.join(dataDir, 'uploads');

    const env = buildSkillRuntimeEnv({
      skillName: 'vehicle-damage-inspection',
      dataDir,
      uploadRoot,
    });

    expect(env.RZYX_AI_DATA_DIR).toBe(path.resolve(dataDir));
    expect(env.RZYX_AI_UPLOAD_ROOT).toBe(path.resolve(uploadRoot));
    expect(env.RZYX_AI_WORKSPACE_ROOT).toBe(
      path.join(path.resolve(dataDir), 'workspace', 'vehicle-damage-inspection'),
    );
  });

  it('uses generic workspace directory for other compute-entry skills', () => {
    const dataDir = path.resolve('C:\\RZYX_AI_DATA');
    const env = buildSkillRuntimeEnv({
      skillName: 'ocr-reader',
      dataDir,
      uploadRoot: path.join(dataDir, 'uploads'),
    });

    expect(env.RZYX_AI_WORKSPACE_ROOT).toBe(
      path.join(path.resolve(dataDir), 'workspace', 'ocr-reader'),
    );
  });

  it.each(['../escape', 'bad--name', 'BadName'])('rejects invalid skill name %s', (skillName) => {
    expect(() => buildSkillRuntimeEnv({
      skillName,
      dataDir: path.resolve('C:\\RZYX_AI_DATA'),
      uploadRoot: path.resolve('C:\\RZYX_AI_DATA\\uploads'),
    })).toThrow(`Invalid skill name for runtime workspace: ${skillName}`);
  });
});

describe('mergeSkillProcessEnv', () => {
  it('keeps runtime RZYX_AI paths authoritative over skill secrets', () => {
    const env = mergeSkillProcessEnv(
      {
        PATH: 'base-path',
        RZYX_AI_DATA_DIR: 'base-data',
      },
      {
        SKILL_TOKEN: 'secret-token',
        RZYX_AI_DATA_DIR: 'secret-data',
        RZYX_AI_UPLOAD_ROOT: 'secret-upload',
        RZYX_AI_WORKSPACE_ROOT: 'secret-workspace',
      },
      {
        RZYX_AI_DATA_DIR: 'runtime-data',
        RZYX_AI_UPLOAD_ROOT: 'runtime-upload',
        RZYX_AI_WORKSPACE_ROOT: 'runtime-workspace',
      },
    );

    expect(env).toEqual({
      PATH: 'base-path',
      SKILL_TOKEN: 'secret-token',
      RZYX_AI_DATA_DIR: 'runtime-data',
      RZYX_AI_UPLOAD_ROOT: 'runtime-upload',
      RZYX_AI_WORKSPACE_ROOT: 'runtime-workspace',
    });
  });
});
