/**
 * DSS Configuration Manager
 *
 * Manages local and project configuration.
 */

import Conf from 'conf';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { join } from 'path';

// Global user config (stored in home directory)
const globalConfig = new Conf({
  projectName: 'dss',
  schema: {
    figmaToken: { type: 'string' },
    defaultPort: { type: 'number', default: 3456 },
    defaultFormat: { type: 'string', default: 'css' },
  },
});

// Project-level config file
const PROJECT_CONFIG_FILE = '.dss/config.json';

export interface DSSConfig {
  figmaFileKey?: string;
  figmaToken?: string;
  port?: number;
  outputDir?: string;
  tokenFormat?: 'css' | 'scss' | 'json' | 'ts';
  componentFramework?: 'react' | 'vue' | 'svelte' | 'webcomponent';
}

export function getProjectRoot(): string {
  return process.cwd();
}

export function getProjectConfigPath(): string {
  return join(getProjectRoot(), PROJECT_CONFIG_FILE);
}

export function hasProjectConfig(): boolean {
  return existsSync(getProjectConfigPath());
}

export function loadProjectConfig(): DSSConfig {
  const configPath = getProjectConfigPath();
  if (!existsSync(configPath)) {
    return {};
  }

  try {
    const content = readFileSync(configPath, 'utf-8');
    return JSON.parse(content);
  } catch (error) {
    console.warn('Failed to parse project config:', error);
    return {};
  }
}

export function saveProjectConfig(config: DSSConfig): void {
  const configPath = getProjectConfigPath();
  const dir = join(getProjectRoot(), '.dss');

  // Ensure .dss directory exists
  if (!existsSync(dir)) {
    const { mkdirSync } = require('fs');
    mkdirSync(dir, { recursive: true });
  }

  writeFileSync(configPath, JSON.stringify(config, null, 2));
}

export function getConfig(): DSSConfig {
  const project = loadProjectConfig();
  return {
    figmaToken: project.figmaToken || globalConfig.get('figmaToken') as string | undefined,
    figmaFileKey: project.figmaFileKey,
    port: project.port || globalConfig.get('defaultPort') as number,
    outputDir: project.outputDir || '.dss/output',
    tokenFormat: project.tokenFormat || (globalConfig.get('defaultFormat') as DSSConfig['tokenFormat']),
    componentFramework: project.componentFramework || 'react',
  };
}

export function setGlobalConfig(key: string, value: string | number): void {
  globalConfig.set(key, value);
}

export function getGlobalConfig(key: string): unknown {
  return globalConfig.get(key);
}

export function listGlobalConfig(): Record<string, unknown> {
  return globalConfig.store;
}
