import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';

export interface Config {
  apiUrl: string;
  clientId: string;
  clientSecret: string;
}

const CONFIG_DIR = path.join(os.homedir(), '.sentryagent');
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');

export function readConfig(): Config | null {
  if (!fs.existsSync(CONFIG_FILE)) {
    return null;
  }
  try {
    const raw = fs.readFileSync(CONFIG_FILE, 'utf-8');
    const parsed: unknown = JSON.parse(raw);
    if (
      parsed !== null &&
      typeof parsed === 'object' &&
      'apiUrl' in parsed &&
      'clientId' in parsed &&
      'clientSecret' in parsed &&
      typeof (parsed as Record<string, unknown>)['apiUrl'] === 'string' &&
      typeof (parsed as Record<string, unknown>)['clientId'] === 'string' &&
      typeof (parsed as Record<string, unknown>)['clientSecret'] === 'string'
    ) {
      const p = parsed as Record<string, unknown>;
      return {
        apiUrl: p['apiUrl'] as string,
        clientId: p['clientId'] as string,
        clientSecret: p['clientSecret'] as string,
      };
    }
    return null;
  } catch {
    return null;
  }
}

export function writeConfig(config: Config): void {
  if (!fs.existsSync(CONFIG_DIR)) {
    fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
  }
  fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), {
    encoding: 'utf-8',
    mode: 0o600,
  });
}

export function requireConfig(): Config {
  const config = readConfig();
  if (config === null) {
    console.error('Not configured. Run `sentryagent configure` first.');
    process.exit(1);
  }
  return config;
}
