import { describe, expect, it } from 'vitest';
import { VoiceInput, MockAudioRecorder, MockSpeechToText, DEFAULT_VOICE_CONFIG } from '../src/ai/voiceInput';
import { calculatePosterStats, SharePosterService, MockViewShotter, type PosterConfig } from '../src/services/sharePoster';
import { exportToExcel, exportToExcelMultiSheet, exportToCsv, transactionToRow, transactionsToRows, MockExcelWorkbook } from '../src/services/data/exportToExcel';
import type { Transaction } from '../src/domain/core/types';

const tx = (over: Partial<Transaction>): Transaction => ({
  id: 't1', date: '2026-07-10', flag: '*', postings: [], tags: [], links: [], source: 'mobile.bean', raw: '',
  ...over,
});

const sampleTx: Transaction[] = [
  tx({ id: 't1', date: '2026-07-05', postings: [{ account: 'Assets:Alipay', amount: '-100', currency: 'CNY' }, { account: 'Expenses:Food', amount: '100', currency: 'CNY' }], tags: ['food'] }),
  tx({ id: 't2', date: '2026-07-10', postings: [{ account: 'Assets:Bank', amount: '5000', currency: 'CNY' }, { account: 'Income:Salary', amount: '-5000', currency: 'CNY' }] }),
  tx({ id: 't3', date: '2026-07-15', postings: [{ account: 'Assets:Alipay', amount: '-200', currency: 'CNY' }, { account: 'Expenses:Food', amount: '200', currency: 'CNY' }] }),
];

// ============ voiceInput ============

describe('voiceInput', () => {
  it('DEFAULT_VOICE_CONFIG 默认 press-to-talk', () => {
    expect(DEFAULT_VOICE_CONFIG.mode).toBe('press-to-talk');
  });

  it('startRecording 请求权限并开始', async () => {
    const recorder = new MockAudioRecorder();
    const stt = new MockSpeechToText('花了30元');
    const voice = new VoiceInput(recorder, stt, { config: { id: 'x', name: 'x', apiKey: '', baseUrl: '', model: '' }, chat: async () => '{}' } as never);
    await voice.startRecording();
    expect(recorder.startCount).toBe(1);
  });

  it('未授权权限时 startRecording 抛错', async () => {
    const recorder = new MockAudioRecorder();
    recorder.permissionGranted = false;
    const voice = new VoiceInput(recorder, new MockSpeechToText(), { config: { id: '', name: '', apiKey: '', baseUrl: '', model: '' }, chat: async () => '' } as never);
    await expect(voice.startRecording()).rejects.toThrow('录音权限');
  });

  it('stopAndProcess 返回转写 + 解析', async () => {
    const recorder = new MockAudioRecorder();
    const stt = new MockSpeechToText('星巴克花了35');
    const aiResponse = JSON.stringify({ type: 'expense', amount: '35', currency: 'CNY', counterparty: '星巴克', narration: '咖啡', time: '2026-07-13' });
    const voice = new VoiceInput(recorder, stt, { config: { id: '', name: '', apiKey: '', baseUrl: '', model: '' }, chat: async () => aiResponse } as never);
    await voice.startRecording();
    const result = await voice.stopAndProcess();
    expect(result.transcription).toBe('星巴克花了35');
    expect(result.parsed?.type).toBe('draft');
  });

  it('空转写返回 null parsed', async () => {
    const recorder = new MockAudioRecorder();
    const stt = new MockSpeechToText('');
    const voice = new VoiceInput(recorder, stt, { config: { id: '', name: '', apiKey: '', baseUrl: '', model: '' }, chat: async () => '' } as never);
    await voice.startRecording();
    const result = await voice.stopAndProcess();
    expect(result.transcription).toBe('');
    expect(result.parsed).toBeNull();
  });

  it('未录音时 stopAndProcess 抛错', async () => {
    const voice = new VoiceInput(new MockAudioRecorder(), new MockSpeechToText(), { config: { id: '', name: '', apiKey: '', baseUrl: '', model: '' }, chat: async () => '' } as never);
    await expect(voice.stopAndProcess()).rejects.toThrow('未在录音');
  });
});

// ============ sharePoster ============

describe('sharePoster', () => {
  it('calculatePosterStats month 类型', () => {
    const config: PosterConfig = {
      type: 'month', title: '7月报告', transactions: sampleTx, year: 2026, month: 7,
    };
    const stats = calculatePosterStats(config);
    expect(stats.totalExpense).toBe('300');
    expect(stats.totalIncome).toBe('5000');
    expect(stats.transactionCount).toBe(3);
    expect(stats.topCategory?.category).toContain('Food');
  });

  it('calculatePosterStats year 类型含 annualReport', () => {
    const config: PosterConfig = {
      type: 'year', title: '2026年报', transactions: sampleTx, year: 2026,
    };
    const stats = calculatePosterStats(config);
    expect(stats.annualReport).toBeDefined();
    expect(stats.annualReport?.transactionCount).toBe(3);
  });

  it('SharePosterService generateAndSave', async () => {
    const shotter = new MockViewShotter();
    const service = new SharePosterService(shotter);
    const uri = await service.generateAndSave(
      { type: 'month', title: '测试', transactions: sampleTx, year: 2026, month: 7 },
      'poster-ref',
    );
    expect(uri).toContain('poster-ref');
    expect(shotter.captured).toHaveLength(1);
    expect(shotter.savedToAlbum).toHaveLength(1);
  });

  it('SharePosterService generateAndShare', async () => {
    const shotter = new MockViewShotter();
    const service = new SharePosterService(shotter);
    await service.generateAndShare(
      { type: 'month', title: '分享', transactions: [], year: 2026, month: 7 },
      'ref',
    );
    expect(shotter.shared).toHaveLength(1);
  });

  it('previewStats 仅计算不截图', () => {
    const shotter = new MockViewShotter();
    const service = new SharePosterService(shotter);
    const stats = service.previewStats({ type: 'month', title: 'x', transactions: sampleTx, year: 2026, month: 7 });
    expect(stats.totalExpense).toBe('300');
    expect(shotter.captured).toHaveLength(0);
  });
});

// ============ exportToExcel ============

describe('exportToExcel', () => {
  it('transactionToRow 转换', () => {
    const row = transactionToRow(sampleTx[0]);
    expect(row.日期).toBe('2026-07-05');
    expect(row.支出).toBe('100');
    expect(row.账户).toContain('Food');
    expect(row.标签).toBe('#food');
  });

  it('transactionsToRows 批量', () => {
    const rows = transactionsToRows(sampleTx);
    expect(rows).toHaveLength(3);
  });

  it('exportToExcel 单工作表', async () => {
    const wb = new MockExcelWorkbook();
    const path = await exportToExcel(sampleTx, wb, '/tmp/test.xlsx');
    expect(path).toBe('/tmp/test.xlsx');
    expect(wb.sheets).toHaveLength(1);
    expect(wb.sheets[0].name).toBe('交易');
    expect(wb.sheets[0].rows).toHaveLength(3);
  });

  it('exportToExcelMultiSheet 多工作表', async () => {
    const wb = new MockExcelWorkbook();
    await exportToExcelMultiSheet(sampleTx, wb, '/tmp/multi.xlsx');
    expect(wb.sheets.length).toBeGreaterThanOrEqual(2);
    expect(wb.sheets.some(s => s.name === '交易')).toBe(true);
    expect(wb.sheets.some(s => s.name === '账户余额')).toBe(true);
  });

  it('exportToCsv 降级 CSV', () => {
    const csv = exportToCsv(sampleTx);
    expect(csv).toContain('日期,摘要,收入,支出');
    expect(csv).toContain('2026-07-05');
    expect(csv.split('\n').length).toBe(4);  // header + 3 rows
  });
});
