import { tradingViewCapture } from './tradingview'
import { aiAnalysisService } from './ai-analysis'
import prisma from './prisma'

export interface AutoTradingConfig {
  enabled: boolean
  symbols: string[]
  intervalMinutes: number
  maxDailyTrades: number
  tradingAmount: number
  confidenceThreshold: number
}

export class AutoTradingService {
  private config: AutoTradingConfig
  private intervalId: NodeJS.Timeout | null = null
  private dailyTradeCount: Record<string, number> = {}

  constructor(config: AutoTradingConfig) {
    this.config = config
    this.dailyTradeCount = {}
  }

  start() {
    if (this.intervalId || !this.config.enabled) return
    this.intervalId = setInterval(() => this.run(), this.config.intervalMinutes * 60 * 1000)
    this.run() // Run immediately on start
  }

  stop() {
    if (this.intervalId) {
      clearInterval(this.intervalId)
      this.intervalId = null
    }
  }

  async run() {
    if (!this.config.enabled) return
    for (const symbol of this.config.symbols) {
      if ((this.dailyTradeCount[symbol] || 0) >= this.config.maxDailyTrades) continue
      // 1. Capture screenshot
      const filename = `${symbol}_${Date.now()}.png`
      const screenshotPath = await tradingViewCapture.capture(symbol, filename)
      // 2. Analyze screenshot
      const analysis = await aiAnalysisService.analyzeScreenshot(filename)
      if (!analysis || analysis.confidence < this.config.confidenceThreshold) continue
      // 3. Execute trade (stub: integrate with driftTradingService)
      // const tradeResult = await driftTradingService.executeTrade({ ... })
      // 4. Save trade to DB
      await prisma.trade.create({
        data: {
          symbol,
          side: analysis.recommendation === 'BUY' ? 'LONG' : analysis.recommendation === 'SELL' ? 'SHORT' : 'NONE',
          amount: this.config.tradingAmount,
          price: 0, // To be filled with actual execution price
          status: 'PENDING',
          screenshotUrl: screenshotPath,
          aiAnalysis: JSON.stringify(analysis),
          executedAt: new Date(),
          userId: 'system', // Or actual user if available
        }
      })
      this.dailyTradeCount[symbol] = (this.dailyTradeCount[symbol] || 0) + 1
    }
  }

  setConfig(config: Partial<AutoTradingConfig>) {
    this.config = { ...this.config, ...config }
  }
}

export function getAutoTradingService() {
  // Singleton pattern or similar
  return new AutoTradingService({
    enabled: false,
    symbols: ['BTCUSD'],
    intervalMinutes: 15,
    maxDailyTrades: 10,
    tradingAmount: 100,
    confidenceThreshold: 80
  })
}
