const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');

function emitEvent(stage, message, extra = {}) {
  const event = {
    type: 'process_event',
    time: new Date().toISOString(),
    stage,
    message,
    ...extra,
  };
  process.stderr.write(`[vehicle-damage-inspection] ${JSON.stringify(event)}\n`);
}

function safeTaskId(value) {
  const raw = String(value || '').trim();
  if (raw && /^[a-zA-Z0-9_-]{1,80}$/.test(raw)) return raw;
  return `task_${Date.now().toString(36)}_${crypto.randomBytes(4).toString('hex')}`;
}

function createWorkspace({ taskId, workspaceRoot }) {
  const root = path.resolve(workspaceRoot);
  fs.mkdirSync(root, { recursive: true });
  const id = safeTaskId(taskId);
  const workspacePath = path.join(root, id);
  fs.mkdirSync(workspacePath, { recursive: true });
  for (const name of ['source', 'frames', 'marked_frames']) {
    fs.mkdirSync(path.join(workspacePath, name), { recursive: true });
  }
  emitEvent('workspace', 'workspace ready', { taskId: id, workspacePath });
  return { taskId: id, workspaceRoot: root, workspacePath };
}

function writeJson(workspace, relativePath, value) {
  const target = path.join(workspace.workspacePath, relativePath);
  fs.mkdirSync(path.dirname(target), { recursive: true });
  fs.writeFileSync(target, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
  return target;
}

function readJson(workspace, relativePath) {
  return JSON.parse(fs.readFileSync(path.join(workspace.workspacePath, relativePath), 'utf8'));
}

function toRelative(workspace, filePath) {
  return path.relative(workspace.workspacePath, filePath).replace(/\\/g, '/');
}

function resolveVideoPath(videoUrl, { uploadRoot }) {
  const value = String(videoUrl || '');
  if (/^https?:\/\//i.test(value)) {
    const url = new URL(value);
    if (!['127.0.0.1', 'localhost'].includes(url.hostname)) {
      throw new Error('第一版仅支持本机 URL、本地路径和 /upload/... 路径');
    }
    const pathname = decodeURIComponent(url.pathname);
    return resolveVideoPath(pathname, { uploadRoot });
  }
  if (fs.existsSync(value)) return path.resolve(value);
  const normalized = value.replace(/\\/g, '/');
  if (normalized.startsWith('/upload/')) {
    if (!uploadRoot) throw new Error('缺少 RZYX_AI_UPLOAD_ROOT，无法解析 /upload 路径');
    const relative = normalized.slice('/upload/'.length);
    const resolved = path.resolve(uploadRoot, relative);
    const uploadRootResolved = path.resolve(uploadRoot);
    if (!resolved.startsWith(uploadRootResolved + path.sep)) throw new Error('upload 路径非法');
    if (!fs.existsSync(resolved)) throw new Error(`视频文件不存在: ${resolved}`);
    return resolved;
  }
  throw new Error(`视频文件不存在: ${value}`);
}

function publicUrl(workspace, relativePath) {
  const rootName = path.basename(path.dirname(workspace.workspacePath));
  return `/workspace/${rootName}/${workspace.taskId}/${relativePath.replace(/\\/g, '/')}`;
}

module.exports = {
  emitEvent,
  createWorkspace,
  writeJson,
  readJson,
  toRelative,
  resolveVideoPath,
  publicUrl,
};
