/**
 * agent 启动环境：默认路径 + .env 加载。
 * 发布时由 sync-launcher-env 复制为 packages/agent/lib/launcher-env.js（单文件，无子模块依赖）。
 */

import { existsSync, readFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
import { createRequire } from 'node:module'

const require = createRequire(import.meta.url)

export function resolveMainPackageRoot() {
  try {
    return dirname(require.resolve('@auto-ai/agent/package.json'))
  } catch {
    return null
  }
}

/**
 * 解析 WS_AGENTS_ROOT：显式环境变量优先，否则 <WS_PROJECT_ROOT|cwd>/.ws-agents。
 */
export function resolveWsAgentsRoot(env) {
  const fromEnv = env.WS_AGENTS_ROOT?.trim()
  if (fromEnv) {
    return fromEnv
  }
  const projectRoot = env.WS_PROJECT_ROOT?.trim() || process.cwd()
  return join(projectRoot, '.ws-agents')
}

function applyDotenvLines(env, text) {
  for (const line of text.split('\n')) {
    const trimmed = line.trim()
    if (!trimmed || trimmed.startsWith('#')) continue
    const eq = trimmed.indexOf('=')
    if (eq <= 0) continue
    const key = trimmed.slice(0, eq).trim()
    let value = trimmed.slice(eq + 1).trim()
    if (
      (value.startsWith('"') && value.endsWith('"')) ||
      (value.startsWith("'") && value.endsWith("'"))
    ) {
      value = value.slice(1, -1)
    }
    if (!key) continue
    if (env[key]?.trim()) continue
    env[key] = value
  }
}

function loadDotenvFile(env, filePath) {
  if (!existsSync(filePath)) return
  try {
    applyDotenvLines(env, readFileSync(filePath, 'utf8'))
  } catch {
    /* 忽略不可读文件 */
  }
}

export function buildLauncherEnv(baseEnv = process.env) {
  const env = { ...baseEnv }
  const cwd = process.cwd()
  const pkgRoot = resolveMainPackageRoot()
  const pkgDist = pkgRoot ? join(pkgRoot, 'dist') : null
  const pkgSafeADist = pkgDist ? join(pkgDist, 'safe-a') : null
  const pkgWsTestDist = pkgDist ? join(pkgDist, 'ws-test') : null

  if (!env.WS_PROJECT_ROOT?.trim()) {
    env.WS_PROJECT_ROOT = cwd
  }
  if (
    !env.WS_DIST_DIR?.trim() &&
    pkgSafeADist &&
    existsSync(join(pkgSafeADist, 'index.html'))
  ) {
    env.WS_DIST_DIR = pkgSafeADist
  }
  if (
    !env.WS_WS_TEST_DIR?.trim() &&
    pkgWsTestDist &&
    existsSync(join(pkgWsTestDist, 'ws-test.html'))
  ) {
    env.WS_WS_TEST_DIR = pkgWsTestDist
  }

  loadDotenvFile(env, join(cwd, '.env'))
  loadDotenvFile(env, join(homedir(), '.config', 'agent', 'env'))
  loadDotenvFile(env, join(homedir(), '.agent.env'))

  if (!env.WS_AGENTS_ROOT?.trim()) {
    env.WS_AGENTS_ROOT = resolveWsAgentsRoot(env)
  }

  if (!env.AGENT_PACKAGE_ROOT?.trim() && pkgRoot) {
    env.AGENT_PACKAGE_ROOT = pkgRoot
  }

  return env
}

/** 写入当前进程环境（源码直接启动 wsServer 时使用） */
export function applyToProcessEnv() {
  const merged = buildLauncherEnv(process.env)
  for (const [key, value] of Object.entries(merged)) {
    if (!process.env[key]?.trim() && String(value).trim()) {
      process.env[key] = String(value)
    }
  }
}
