// Application configuration
export interface AppConfig {
  adminDid: string;
  collections: {
    comment: string;
    user: string;
    chat: string;
  };
  host: string;
  rkey?: string; // Current post rkey if on post page
  aiEnabled: boolean;
  aiAskAi: boolean;
  aiProvider: string;
  aiModel: string;
  aiHost: string;
  bskyPublicApi: string;
}

// Generate collection names from host
// Format: ${reg}.${name}.${sub}
// Example: log.syui.ai -> ai.syui.log
function generateCollectionNames(host: string): { comment: string; user: string; chat: string } {
  try {
    // Remove protocol if present
    const cleanHost = host.replace(/^https?:\/\//, '');
    
    // Split host into parts
    const parts = cleanHost.split('.');
    
    if (parts.length < 2) {
      throw new Error('Invalid host format');
    }
    
    // Reverse the parts for collection naming
    // log.syui.ai -> ai.syui.log
    const reversedParts = parts.reverse();
    const collectionBase = reversedParts.join('.');
    
    return {
      comment: collectionBase,
      user: `${collectionBase}.user`,
      chat: `${collectionBase}.chat`
    };
  } catch (error) {
    console.warn('Failed to generate collection names from host:', host, error);
    // Fallback to default collections
    return {
      comment: 'ai.syui.log',
      user: 'ai.syui.log.user',
      chat: 'ai.syui.log.chat'
    };
  }
}

// Extract rkey from current URL
// /posts/xxx.html -> xxx
function extractRkeyFromUrl(): string | undefined {
  const pathname = window.location.pathname;
  const match = pathname.match(/\/posts\/([^/]+)\.html$/);
  return match ? match[1] : undefined;
}

// Get application configuration from environment variables
export function getAppConfig(): AppConfig {
  const host = import.meta.env.VITE_APP_HOST || 'https://log.syui.ai';
  const adminDid = import.meta.env.VITE_ADMIN_DID || 'did:plc:uqzpqmrjnptsxezjx4xuh2mn';
  
  // Priority: Environment variables > Auto-generated from host
  const autoGeneratedCollections = generateCollectionNames(host);
  const collections = {
    comment: import.meta.env.VITE_COLLECTION_COMMENT || autoGeneratedCollections.comment,
    user: import.meta.env.VITE_COLLECTION_USER || autoGeneratedCollections.user,
    chat: import.meta.env.VITE_COLLECTION_CHAT || autoGeneratedCollections.chat,
  };
  
  const rkey = extractRkeyFromUrl();
  
  // AI configuration
  const aiEnabled = import.meta.env.VITE_AI_ENABLED === 'true';
  const aiAskAi = import.meta.env.VITE_AI_ASK_AI === 'true';
  const aiProvider = import.meta.env.VITE_AI_PROVIDER || 'ollama';
  const aiModel = import.meta.env.VITE_AI_MODEL || 'gemma2:2b';
  const aiHost = import.meta.env.VITE_AI_HOST || 'https://ollama.syui.ai';
  const bskyPublicApi = import.meta.env.VITE_BSKY_PUBLIC_API || 'https://public.api.bsky.app';
  
  console.log('App configuration:', {
    host,
    adminDid,
    collections,
    rkey: rkey || 'none (not on post page)',
    ai: { enabled: aiEnabled, askAi: aiAskAi, provider: aiProvider, model: aiModel, host: aiHost },
    bskyPublicApi
  });
  
  return {
    adminDid,
    collections,
    host,
    rkey,
    aiEnabled,
    aiAskAi,
    aiProvider,
    aiModel,
    aiHost,
    bskyPublicApi
  };
}

// Export singleton instance
export const appConfig = getAppConfig();