import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import { fileURLToPath } from 'node:url';

// ESM 下 __dirname 不可用，用 import.meta.url 重建
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export interface RuntimeInfoLite {
  port: number;
  controlSecret: string;
  controlBaseUrl: string;
}

export function readRuntimeInfo(): RuntimeInfoLite {
  if (process.env.NETA_RUNTIME_INFO) {
    return JSON.parse(fs.readFileSync(process.env.NETA_RUNTIME_INFO, 'utf8'));
  }
  // __dirname = packages/netabrowser-cli/dist/client
  // 上溯：dist/client → dist → cli → packages，再进 backend/dist
  const candidates = [
    // pkg 模式：exec 同级 data 目录
    path.join(path.dirname(process.execPath), 'data', 'runtime-info.json'),
    // dev 模式（已编译 dist）：cli/dist/client → packages → backend/dist
    path.resolve(__dirname, '../../../backend/dist/runtime-info.json'),
    // dev 模式（源码 ts-node 等）：cli/src/client → packages → backend/dist
    path.resolve(__dirname, '../../../backend/dist/runtime-info.json'),
    // 用户目录后备
    path.join(os.homedir(), '.neta', 'runtime-info.json'),
  ];
  for (const p of candidates) {
    if (fs.existsSync(p)) return JSON.parse(fs.readFileSync(p, 'utf8'));
  }
  throw new Error(
    `runtime-info.json not found. Set NETA_RUNTIME_INFO env var or run backend first.\nTried:\n${candidates.map(c => '  - ' + c).join('\n')}`
  );
}
