/**
 * Configuration loader — VLCode Lite
 * Priority: CLI args → .env file → environment variables → defaults
 */
import path from 'path';
import fs from 'fs';
import os from 'os';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

function readJsonIfExists(filePath) {
  try {
    if (filePath && fs.existsSync(filePath)) {
      return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
    }
  } catch {}
  return null;
}

function resolvePackageJson() {
  const candidates = [
    process.env.VLCODE_APP_ROOT ? path.join(process.env.VLCODE_APP_ROOT, 'package.json') : '',
    path.resolve(__dirname, '../../package.json'),
    path.resolve(process.cwd(), 'package.json'),
  ].filter(Boolean);

  for (const candidate of candidates) {
    const pkg = readJsonIfExists(candidate);
    if (pkg) return pkg;
  }
  return {};
}

const PKG = resolvePackageJson();
export const APP_VERSION = process.env.VLCODE_APP_VERSION || PKG.version || '0.0.0';

/** Load .env file if present */
function loadEnvFile(dir) {
  const envPath = path.join(dir, '.env');
  try {
    const content = fs.readFileSync(envPath, 'utf-8');
    for (const line of content.split('\n')) {
      const trimmed = line.trim();
      if (!trimmed || trimmed.startsWith('#')) continue;
      const eqIdx = trimmed.indexOf('=');
      if (eqIdx === -1) continue;
      const key = trimmed.slice(0, eqIdx).trim();
      let value = trimmed.slice(eqIdx + 1).trim();
      if ((value.startsWith('"') && value.endsWith('"')) ||
          (value.startsWith("'") && value.endsWith("'"))) {
        value = value.slice(1, -1);
      }
      if (!process.env[key]) {
        process.env[key] = value;
      }
    }
  } catch {
    // No .env file
  }
}

export function loadConfig(args) {
  let workDir = process.cwd();
  let explicitWorkDir = false;
  let webMode = false;
  let emptyWindow = false;
  for (let i = 0; i < args.length; i++) {
    if (args[i] === '--dir' || args[i] === '-d') {
      explicitWorkDir = true;
      workDir = path.resolve(args[++i]);
    } else if (args[i] === '--web' || args[i] === '-w') {
      webMode = true;
    } else if (args[i] === '--empty-window') {
      emptyWindow = true;
    }
  }

  loadEnvFile(workDir);
  loadEnvFile(process.cwd());

  // Note: ANTHROPIC_API_KEY is used when available (direct API mode)
  // If not set, falls back to CLI subscription

  const config = {
    model: process.env.VL_CODE_MODEL || 'claude-opus-4-6',
    maxOutputTokens: parseInt(process.env.VL_CODE_MAX_OUTPUT_TOKENS || '32000', 10),

    workDir,
    explicitWorkDir,

    web: webMode,
    noWorkspace: emptyWindow || (webMode && !explicitWorkDir),
    emptyWorkspaceDir: path.join(os.homedir(), '.vl-code', 'empty-window'),
    port: parseInt(process.env.VL_CODE_PORT || '4000', 10),

    workflowApiUrl: process.env.VL_WORKFLOW_API_URL || 'https://editor.visuallogic.ai/ih5/play/stream',
    workspaceApiUrl: process.env.VL_WORKSPACE_API_URL || 'https://editor.visuallogic.ai/ih5/editor/workspace',
    vlParseApiUrl: process.env.VL_PARSE_API_URL || null,

    workspaceRoot: process.env.VL_WORKSPACE_ROOT || path.join(os.homedir(), 'Documents', 'VLProjects'),
    workflowMode: process.env.VL_WORKFLOW_MODE || 'local',

    apiKey: process.env.ANTHROPIC_API_KEY || undefined,
    llmProvider: process.env.VL_CODE_LLM_PROVIDER || 'cli',

    autotest: {
      headless: false,
      parallelWorkers: 3,
      maxCases: 8,
      useWorkflowEngine: true,
    },
  };

  for (let i = 0; i < args.length; i++) {
    const arg = args[i];
    if (arg === '--dir' || arg === '-d') {
      i++;
    } else if (arg === '--model' || arg === '-m') {
      config.model = args[++i];
    } else if (arg === '--max-tokens') {
      config.maxOutputTokens = parseInt(args[++i], 10);
    } else if (arg === '--web' || arg === '-w') {
      config.web = true;
    } else if (arg === '--empty-window') {
      config.noWorkspace = true;
    } else if (arg === '--port' || arg === '-p') {
      config.port = parseInt(args[++i], 10);
    } else if (arg === '--workflow-mode') {
      config.workflowMode = args[++i];
    } else if (arg === '--help' || arg === '-h') {
      printUsage();
      process.exit(0);
    } else if (arg === '--version' || arg === '-v') {
      console.log(`vlcode-lite v${APP_VERSION}`);
      process.exit(0);
    }
  }

  if (config.noWorkspace) {
    fs.mkdirSync(config.emptyWorkspaceDir, { recursive: true });
    config.workDir = config.emptyWorkspaceDir;
  }

  return config;
}

function printUsage() {
  console.log(`
Usage: vlcode-lite [options]

Options:
  -d, --dir <path>         Working directory (default: cwd)
  -m, --model <model>      Claude model (default: claude-opus-4-6)
  --max-tokens <n>         Max output tokens (default: 32000)
  -w, --web                Start browser IDE
  -p, --port <port>        Web server port (default: 4000)
  --empty-window           Start web IDE without loading a workspace
  --workflow-mode <mode>   local | auto (default: local)
  -h, --help               Show this help
  -v, --version            Show version
`);
}
