/**
 * 模块路径发现工具
 *
 * 根据模块名自动推导前端 API 文件、后端 Controller/DTO 目录、DB schema 等路径。
 * 所有脚本共享此逻辑，避免路径硬编码。
 */

const fs = require('fs') as typeof import('fs');
const path = require('path') as typeof import('path');

const ROOT = path.resolve(__dirname, '..', '..', '..');

export interface ModulePaths {
  /** 模块名，如 'performance', 'asset-management' */
  moduleName: string;
  /** API 路由前缀，如 '/performance', '/asset-management' */
  apiPrefix: string;
  /** 前端 API 文件绝对路径 */
  frontendApiFile: string;
  /** 后端 controllers 目录 */
  backendControllersDir: string;
  /** 后端 dto 目录 */
  backendDtoDir: string;
  /** 后端 services 目录 */
  backendServicesDir: string;
  /** 项目根目录 */
  root: string;
}

/**
 * 从 CLI 参数解析模块名
 * 支持: --module performance 或 --module=performance
 * 默认: performance
 */
export function parseModuleArg(defaultModule = 'performance'): string {
  const args = process.argv.slice(2);
  for (let i = 0; i < args.length; i++) {
    if (args[i] === '--module' && args[i + 1]) return args[i + 1];
    if (args[i].startsWith('--module=')) return args[i].split('=')[1];
  }
  return defaultModule;
}

/**
 * 自动发现前端 API 文件路径
 *
 * 按优先级查找:
 * 1. frontend/src/services/api/{module}.ts                        (全局 API 文件)
 * 2. frontend/src/app/(modules)/{module}/_lib/api/index.ts        (模块本地 API)
 * 3. frontend/src/app/(modules)/{module}/_lib/api.ts              (模块本地 API 单文件)
 */
function discoverFrontendApiFile(moduleName: string): string {
  const candidates = [
    path.join(ROOT, `frontend/src/services/api/${moduleName}.ts`),
    path.join(ROOT, `frontend/src/app/(modules)/${moduleName}/_lib/api/index.ts`),
    path.join(ROOT, `frontend/src/app/(modules)/${moduleName}/_lib/api.ts`),
  ];

  for (const candidate of candidates) {
    if (fs.existsSync(candidate)) return candidate;
  }

  console.error(`❌ 未找到模块 "${moduleName}" 的前端 API 文件`);
  console.error('  已尝试路径:');
  for (const c of candidates) {
    console.error(`    ${path.relative(ROOT, c)}`);
  }
  process.exit(1);
}

/**
 * 根据模块名推导所有路径
 */
export function resolveModulePaths(moduleName: string): ModulePaths {
  const frontendApiFile = discoverFrontendApiFile(moduleName);
  const backendModuleDir = path.join(ROOT, `backend/src/modules/${moduleName}`);

  if (!fs.existsSync(backendModuleDir)) {
    console.error(`❌ 未找到后端模块目录: backend/src/modules/${moduleName}/`);
    process.exit(1);
  }

  // 支持两种布局：
  //  - 子目录：backend/src/modules/{m}/controllers/  (performance 等)
  //  - 根目录扁平：backend/src/modules/{m}/*.controller.ts  (robot-manager)
  const controllersSubDir = path.join(backendModuleDir, 'controllers');
  const backendControllersDir = fs.existsSync(controllersSubDir)
    ? controllersSubDir
    : backendModuleDir;

  return {
    moduleName,
    apiPrefix: `/${moduleName}`,
    frontendApiFile,
    backendControllersDir,
    backendDtoDir: path.join(backendModuleDir, 'dto'),
    backendServicesDir: path.join(backendModuleDir, 'services'),
    root: ROOT,
  };
}

/**
 * 加载模块专属配置（如果存在）
 * 配置文件位于 testing/scripts/module-config/{module}.config.ts
 */
export function loadModuleConfig<T>(moduleName: string, configType: string): T | null {
  const configPath = path.join(__dirname, `${moduleName}.${configType}.ts`);
  if (!fs.existsSync(configPath)) return null;
  try {
    return require(configPath) as T;
  } catch {
    return null;
  }
}
