import fs from 'node:fs';
import { CONFIG_DIR, CONFIG_FILE } from './paths';

export interface AgentConfig {
  apiBaseUrl: string;
  organizationSlug: string;
  developerName: string;
  developerEmail: string;
  deviceId: string;
  deviceToken: string;
  agentVersion: string;
  enabled: boolean;
  excludedProjects: string[];
  excludedDirectories: string[];
}

export type PartialAgentConfig = Partial<AgentConfig>;

function ensureConfigDir(): void {
  fs.mkdirSync(CONFIG_DIR, { recursive: true });
}

export function readConfig(): AgentConfig | null {
  if (!fs.existsSync(CONFIG_FILE)) {
    return null;
  }

  try {
    return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')) as AgentConfig;
  } catch {
    return null;
  }
}

export function writeConfig(config: AgentConfig): void {
  ensureConfigDir();
  fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { mode: 0o600 });
}

export function updateConfig(patch: PartialAgentConfig): AgentConfig {
  const current = readConfig();

  if (!current) {
    throw new Error('Agent is not logged in. Run `prompt-agent login` first.');
  }

  const next = { ...current, ...patch };
  writeConfig(next);

  return next;
}

export function clearConfig(): void {
  if (fs.existsSync(CONFIG_FILE)) {
    fs.unlinkSync(CONFIG_FILE);
  }
}

export function isPathExcluded(config: AgentConfig, absolutePath: string): boolean {
  const normalized = absolutePath.toLowerCase();

  return config.excludedDirectories.some((dir) => normalized.includes(dir.toLowerCase()));
}
