import { NextRequest, NextResponse } from 'next/server'
import * as fs from 'fs'
import * as path from 'path'

const dataFile = path.join(process.cwd(), 'trading-traders.json')

const defaultTraders = [
  {
    id: 'dopetrades',
    name: 'DopeTrades',
    status: 'learning',
    framesAnalyzed: 382,
    patterns: ['Double Top/Bottom', 'Head & Shoulders', 'Triangles', 'Flags', 'Wedges'],
    entryRules: [
      'Identify clear structure (swing highs/lows)',
      'Wait for retest of level',
      'Confirm momentum in desired direction',
      'Higher timeframe alignment',
      'Entry on break of structure or retest',
      'Confirmation candle required'
    ],
    exitRules: [
      'Stop below recent swing low (long)',
      'Take profit minimum 2:1',
      'Scale 50% at 1:1',
      'Trailing stop after 1:1 achieved',
      'Never move stop loss further'
    ],
    indicators: [
      '9 EMA (short term)',
      '20 EMA (medium term)',
      '50 SMA (trend filter)',
      'RSI 14 (momentum)',
      'Volume profile'
    ],
    riskParams: [
      'Max 2% risk per trade',
      'Max 3 concurrent trades',
      '6% daily max loss',
      '10% weekly max loss',
      'Stop after 3 losses'
    ],
    timeframe: 'Multi: 4H/Daily trend, 1H structure, 15min entries',
    notes: 'Frame analysis: 3% bullish, 7% bearish, 90% neutral. Dark charts confirmed.'
  }
]

export async function GET() {
  try {
    let traders = defaultTraders
    if (fs.existsSync(dataFile)) {
      const saved = JSON.parse(fs.readFileSync(dataFile, 'utf-8'))
      if (saved.length > 0) {
        traders = saved
      }
    } else {
      fs.writeFileSync(dataFile, JSON.stringify(defaultTraders, null, 2))
    }
    return NextResponse.json({ traders })
  } catch (error) {
    return NextResponse.json({ traders: defaultTraders })
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    let traders = defaultTraders
    
    if (fs.existsSync(dataFile)) {
      traders = JSON.parse(fs.readFileSync(dataFile, 'utf-8'))
    }

    traders.push({
      ...body,
      id: body.name.toLowerCase().replace(/\s+/g, '-'),
      createdAt: new Date().toISOString()
    })

    fs.writeFileSync(dataFile, JSON.stringify(traders, null, 2))
    return NextResponse.json({ success: true })
  } catch (error) {
    return NextResponse.json({ error: 'Failed to save' }, { status: 500 })
  }
}
