import Conf from 'conf';
import { homedir } from 'os';
import { join } from 'path';

export interface ClawiverseConfig {
  identity?: {
    did: string;
    publicKey: string;
    privateKey: string;
  };
  network?: {
    bootstrapPeers: string[];
    listenAddresses: string[];
  };
  agentCard?: {
    name: string;
    description: string;
    capabilities: string[];
  };
}

const CLAWIVERSE_HOME = process.env.CLAWIVERSE_HOME || join(homedir(), '.clawiverse');

const config = new Conf<ClawiverseConfig>({
  projectName: 'clawiverse',
  cwd: CLAWIVERSE_HOME,
});

export function getConfig(): ClawiverseConfig {
  return config.store;
}

export function setConfig(key: string, value: unknown): void {
  config.set(key, value);
}

export function getConfigValue<T>(key: string): T | undefined {
  return config.get(key) as T | undefined;
}

export function hasIdentity(): boolean {
  return config.has('identity');
}

export function getIdentity() {
  return config.get('identity');
}

export function setIdentity(identity: ClawiverseConfig['identity']): void {
  config.set('identity', identity);
}

export function getAgentCard() {
  return config.get('agentCard');
}

export function setAgentCard(card: ClawiverseConfig['agentCard']): void {
  config.set('agentCard', card);
}

// Default public bootstrap nodes (update after deployment)
const DEFAULT_BOOTSTRAP_PEERS: string[] = [
  '/dns4/hw1.woowot.com/tcp/4001/p2p/12D3KooWH9R8d4bhzpfyWi3aY5wLBsmLp1LU8ZGk9V7rK17sfzaW',
];

export function getBootstrapPeers(): string[] {
  const userPeers = config.get('network.bootstrapPeers') as string[] | undefined;
  if (userPeers && userPeers.length > 0) return userPeers;
  return DEFAULT_BOOTSTRAP_PEERS;
}

export function setBootstrapPeers(peers: string[]): void {
  config.set('network.bootstrapPeers', peers);
}
