#!/usr/bin/env node
'use strict';

// First-run setup — auto-detects owner info and creates .env + config.
// No interactive prompts. API key and integrations are configured via the web UI.

const { execFileSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const { atomicWriteFileSync } = require('../claude-task-manager/atomic-write');
const {
  setupProviderHasRuntimeAccess,
} = require('../claude-task-manager/lib/setup-provider-config');

const ROOT = path.resolve(__dirname, '..');
const ENV_PATH = path.join(ROOT, '.env');
const WALLE_CONFIG = path.join(ROOT, 'wall-e', 'wall-e-config.json');

function detectName() {
  try { return execFileSync('git', ['config', 'user.name'], { encoding: 'utf8' }).trim(); } catch {}
  try { return execFileSync('id', ['-F'], { encoding: 'utf8' }).trim(); } catch {}
  return process.env.USER || 'Owner';
}

function detectTimezone() {
  try { return Intl.DateTimeFormat().resolvedOptions().timeZone; } catch {}
  return 'UTC';
}

/**
 * Returns true if setup was performed, false if already configured.
 */
function runIfNeeded() {
  if (fs.existsSync(ENV_PATH)) return false;

  const ownerName = detectName().replace(/[\r\n=]/g, '').trim().slice(0, 200);
  const timezone = detectTimezone();
  const nameParts = ownerName.split(/\s+/);

  // Write .env
  const envLines = [
    `# Wall-E configuration — generated ${new Date().toISOString().split('T')[0]}`,
    `# Configure API key and integrations at http://localhost:3456/setup`,
    '',
    `WALLE_OWNER_NAME=${ownerName}`,
    '# ANTHROPIC_API_KEY=sk-ant-...',
  ];
  atomicWriteFileSync(ENV_PATH, envLines.join('\n') + '\n', { mode: 0o600 });

  // Set in current process
  process.env.WALLE_OWNER_NAME = ownerName;

  // Write wall-e-config.json if missing
  if (!fs.existsSync(WALLE_CONFIG)) {
    const config = {
      owner: {
        name: ownerName,
        first_name: nameParts[0],
        last_name: nameParts.slice(1).join(' '),
        timezone,
      },
      adapters: { ctm: { enabled: true }, slack: { enabled: false } },
      intervals: { ingest_ms: 60000, think_ms: 120000 },
    };
    fs.mkdirSync(path.dirname(WALLE_CONFIG), { recursive: true });
    fs.writeFileSync(WALLE_CONFIG, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
  }

  // Create data directory
  const dataDir = process.env.WALL_E_DATA_DIR || path.join(process.env.HOME, '.walle', 'data');
  fs.mkdirSync(dataDir, { recursive: true });

  console.log(`[setup] First-run setup complete. Owner: ${ownerName}`);
  console.log(`[setup] Finish setup at http://localhost:3456/setup`);
  return true;
}

/** Returns true if setup is needed (no API key configured anywhere). Cached after first check. */
let _needsSetupCache = undefined;

function parseEnvFile(content) {
  const out = {};
  for (const line of String(content || '').split('\n')) {
    const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/);
    if (!m) continue;
    out[m[1]] = m[2].replace(/^['"]|['"]$/g, '');
  }
  return out;
}

function readEnvFile() {
  if (!fs.existsSync(ENV_PATH)) return {};
  try { return parseEnvFile(fs.readFileSync(ENV_PATH, 'utf8')); }
  catch { return {}; }
}

function readBrainProviderState(env) {
  try {
    const brain = require('../wall-e/brain');
    if (typeof brain.getDb === 'function') brain.getDb();
    const provider = brain.getKv?.('walle_provider') || env.WALLE_PROVIDER || 'anthropic';
    const row = brain.getDb().prepare(
      'SELECT api_key_encrypted, auth_method FROM model_providers WHERE type = ? AND enabled = 1 ORDER BY updated_at DESC LIMIT 1'
    ).get(provider);
    return {
      provider,
      authMethod: row?.auth_method || brain.getProviderAuthMethod?.(provider) || env.WALLE_AUTH_METHOD || '',
      hasStoredKey: !!row?.api_key_encrypted,
    };
  } catch {
    return null;
  }
}

function needsSetup() {
  if (_needsSetupCache !== undefined) return _needsSetupCache;
  if (!fs.existsSync(ENV_PATH)) {
    const provider = process.env.WALLE_PROVIDER || 'anthropic';
    _needsSetupCache = !setupProviderHasRuntimeAccess({
      type: provider,
      env: process.env,
      authMethod: process.env.WALLE_AUTH_METHOD || '',
      hasStoredKey: false,
    });
    return _needsSetupCache;
  }
  const fileEnv = readEnvFile();
  const env = { ...fileEnv, ...process.env };
  const dbState = readBrainProviderState(env);
  const provider = dbState?.provider || env.WALLE_PROVIDER || 'anthropic';
  const authMethod = dbState?.authMethod || env.WALLE_AUTH_METHOD || '';
  const hasStoredKey = !!dbState?.hasStoredKey;
  _needsSetupCache = !setupProviderHasRuntimeAccess({ type: provider, env, authMethod, hasStoredKey });
  return _needsSetupCache;
}

/** Call after saving API key to clear the needsSetup cache. */
function clearSetupCache() { _needsSetupCache = undefined; }

module.exports = { runIfNeeded, needsSetup, clearSetupCache };

if (require.main === module) {
  const ran = runIfNeeded();
  if (!ran) console.log('Already configured.');
}
