import { test, expect } from '@playwright/test'
import { API_BASE, seedUsageStats, clearDatabase } from './fixtures'

test.describe('统计概览', () => {
  test.beforeAll(async ({ request }) => {
    await clearDatabase(request)
    const p1 = `sp1_${Date.now()}`
    const p2 = `sp2_${Date.now()}`
    process.env._STATS_P1 = p1
    process.env._STATS_P2 = p2

    for (const id of [p1, p2]) {
      await request.post(`${API_BASE}/api/providers`, {
        data: {
          id,
          name: `Stats Provider ${id}`,
          api_key: 'sk_test',
          base_url: 'https://api.example.com/v1',
          protocol: 'openai',
          enabled: true,
        },
      })
    }

    const today = new Date()
    const statsData = []
    for (let i = 0; i < 7; i++) {
      const d = new Date(today)
      d.setDate(d.getDate() - i)
      const dateStr = d.toISOString().slice(0, 10)
      statsData.push({ providerId: p1, modelName: 'gpt_4', requestCount: 10 + i, date: dateStr })
      if (i < 3) {
        statsData.push({ providerId: p1, modelName: 'claude_3', requestCount: 5 + i, date: dateStr })
      }
      if (i < 5) {
        statsData.push({ providerId: p2, modelName: 'gpt_4', requestCount: 8 + i, date: dateStr })
      }
    }
    await seedUsageStats(statsData)
  })

  test.beforeEach(async ({ page }) => {
    await page.goto('/stats')
    await expect(page.getByRole('heading', { name: '用量统计' })).toBeVisible()
  })

  test('应显示正确的总请求量', async ({ page }) => {
    await page.waitForTimeout(1000)
    await expect(page.getByText('总请求量')).toBeVisible()
  })

  test('应显示正确的活跃模型数和活跃供应商数', async ({ page }) => {
    await page.waitForTimeout(1000)
    await expect(page.getByText('活跃模型数')).toBeVisible()
    await expect(page.getByText('活跃供应商数')).toBeVisible()
  })

  test('应显示统计数据行', async ({ page }) => {
    await expect(page.locator('.t-table__body tr').first()).toBeVisible({ timeout: 5000 })
  })

  test('应渲染趋势图表区域', async ({ page }) => {
    await expect(page.getByText('请求趋势')).toBeVisible()
  })
})

test.describe('统计筛选', () => {
  test.beforeAll(async ({ request }) => {
    await clearDatabase(request)
    const p1 = `fp1_${Date.now()}`
    const p2 = `fp2_${Date.now()}`
    process.env._FILTER_P1 = p1
    process.env._FILTER_P2 = p2

    for (const id of [p1, p2]) {
      await request.post(`${API_BASE}/api/providers`, {
        data: {
          id,
          name: `Filter Provider ${id}`,
          api_key: 'sk_test',
          base_url: 'https://api.example.com/v1',
          protocol: 'openai',
          enabled: true,
        },
      })
    }

    const today = new Date()
    const statsData = []
    for (let i = 0; i < 3; i++) {
      const d = new Date(today)
      d.setDate(d.getDate() - i)
      const dateStr = d.toISOString().slice(0, 10)
      statsData.push({ providerId: p1, modelName: 'gpt_4', requestCount: 10 + i, date: dateStr })
      statsData.push({ providerId: p2, modelName: 'claude_3', requestCount: 5 + i, date: dateStr })
    }
    await seedUsageStats(statsData)
  })

  test.beforeEach(async ({ page }) => {
    await page.goto('/stats')
    await expect(page.getByRole('heading', { name: '用量统计' })).toBeVisible()
  })

  test('按供应商筛选', async ({ page }) => {
    await expect(page.locator('.t-table__body tr').first()).toBeVisible({ timeout: 5000 })
    const rowCountBefore = await page.locator('.t-table__body tr:not(.t-table__empty-row)').count()

    await page.locator('.t-select').first().click()
    await page.waitForSelector('.t-select__dropdown', { timeout: 3000 })
    await page.locator('.t-select__dropdown .t-select-option').first().click()
    await page.waitForTimeout(1000)

    const rowCountAfter = await page.locator('.t-table__body tr:not(.t-table__empty-row)').count()
    expect(rowCountAfter).toBeLessThanOrEqual(rowCountBefore)
  })

  test('按模型名称筛选', async ({ page }) => {
    await expect(page.locator('.t-table__body tr').first()).toBeVisible({ timeout: 5000 })
    await page.getByPlaceholder('模型名称').fill('gpt_4')
    await page.waitForTimeout(1000)
    await expect(page.locator('.t-table__body')).toBeVisible()
  })

  test('应显示筛选栏', async ({ page }) => {
    await expect(page.locator('.t-select').first()).toBeVisible()
    await expect(page.getByPlaceholder('模型名称')).toBeVisible()
  })
})
