import { readFileSync, writeFileSync, mkdirSync, chmodSync } from 'fs';
import { resolve } from 'path';
import { homedir } from 'os';

const AUTH_DIR = resolve(homedir(), '.config/flynn');
const AUTH_FILE = resolve(AUTH_DIR, 'auth.json');

export interface GeminiAuthInfo {
  /** Gemini API key. */
  api_key: string;
  created_at: string;
}

interface AuthStore {
  gemini?: GeminiAuthInfo;
  [key: string]: unknown;
}

function safeJsonParse<T>(raw: string): T | null {
  try {
    return JSON.parse(raw) as T;
  } catch {
    return null;
  }
}

function readAuthStore(): AuthStore {
  try {
    const raw = readFileSync(AUTH_FILE, 'utf-8');
    const parsed = safeJsonParse<AuthStore>(raw);
    return parsed ?? {};
  } catch {
    return {};
  }
}

function writeAuthStore(store: AuthStore): void {
  mkdirSync(AUTH_DIR, { recursive: true });
  writeFileSync(AUTH_FILE, JSON.stringify(store, null, 2) + '\n', 'utf-8');
  chmodSync(AUTH_FILE, 0o600);
}

export function loadStoredGeminiAuth(): GeminiAuthInfo | null {
  const store = readAuthStore();
  return store.gemini ?? null;
}

export function storeGeminiAuth(apiKey: string): void {
  const trimmed = apiKey.trim();
  if (!trimmed) {
    throw new Error('Gemini API key is empty');
  }
  const store = readAuthStore();
  store.gemini = { api_key: trimmed, created_at: new Date().toISOString() };
  writeAuthStore(store);
}

export function clearGeminiAuth(): void {
  const store = readAuthStore();
  delete store.gemini;
  writeAuthStore(store);
}

/**
 * Get a Gemini API key from any available source.
 * Priority: GEMINI_API_KEY -> GOOGLE_API_KEY -> stored auth.json.
 */
export function getGeminiApiKey(): string | null {
  return process.env.GEMINI_API_KEY
    ?? process.env.GOOGLE_API_KEY
    ?? loadStoredGeminiAuth()?.api_key
    ?? null;
}
