import fs from 'fs/promises'
import path from 'path'

export interface TradingSettings {
  symbol: string
  timeframe: string
  layouts: string[]
  lastUpdated: number
}

const SETTINGS_FILE = path.join(process.cwd(), 'trading-settings.json')

export class SettingsManager {
  private static instance: SettingsManager
  private settings: TradingSettings = {
    symbol: 'BTCUSD',
    timeframe: '5',
    layouts: ['ai'],
    lastUpdated: Date.now()
  }

  private constructor() {}

  static getInstance(): SettingsManager {
    if (!SettingsManager.instance) {
      SettingsManager.instance = new SettingsManager()
    }
    return SettingsManager.instance
  }

  async loadSettings(): Promise<TradingSettings> {
    try {
      const data = await fs.readFile(SETTINGS_FILE, 'utf-8')
      this.settings = JSON.parse(data)
      console.log('Loaded settings:', this.settings)
    } catch (error) {
      console.log('No existing settings found, using defaults')
      await this.saveSettings()
    }
    return this.settings
  }

  async saveSettings(): Promise<void> {
    try {
      this.settings.lastUpdated = Date.now()
      await fs.writeFile(SETTINGS_FILE, JSON.stringify(this.settings, null, 2))
      console.log('Settings saved:', this.settings)
    } catch (error) {
      console.error('Failed to save settings:', error)
    }
  }

  async updateSettings(updates: Partial<TradingSettings>): Promise<TradingSettings> {
    this.settings = { ...this.settings, ...updates }
    await this.saveSettings()
    return this.settings
  }

  getSettings(): TradingSettings {
    return this.settings
  }

  async setSymbol(symbol: string): Promise<void> {
    await this.updateSettings({ symbol })
  }

  async setTimeframe(timeframe: string): Promise<void> {
    await this.updateSettings({ timeframe })
  }

  async setLayouts(layouts: string[]): Promise<void> {
    await this.updateSettings({ layouts })
  }

  async addLayout(layout: string): Promise<void> {
    if (!this.settings.layouts.includes(layout)) {
      const layouts = [...this.settings.layouts, layout]
      await this.updateSettings({ layouts })
    }
  }

  async removeLayout(layout: string): Promise<void> {
    const layouts = this.settings.layouts.filter(l => l !== layout)
    await this.updateSettings({ layouts })
  }
}

export const settingsManager = SettingsManager.getInstance()
