/**
 * AI驱动测试自动化 - 类型定义
 * 
 * @module testing/tools/types
 * @version 1.0.0
 */

/**
 * 测试优先级
 */
export type TestPriority = 'P0' | 'P1' | 'P2';

/**
 * 测试状态
 */
export type TestStatus = 'pending' | 'running' | 'passed' | 'failed' | 'skipped';

/**
 * AI修复Level
 */
export type FixLevel = 'level1' | 'level2' | 'level3';

/**
 * 问题类别
 */
export type ProblemCategory =
  | 'missing_data_testid'
  | 'selector_changed'
  | 'outdated_doc_content'
  | 'api_change'
  | 'business_logic_change'
  | 'performance_issue'
  | 'security_issue'
  | 'architecture_issue'
  | 'unknown';

/**
 * 回归策略
 */
export type RegressionStrategy =
  | 'minimal'      // 策略1：最小范围
  | 'module'       // 策略2：模块范围
  | 'dependency'   // 策略3：依赖范围
  | 'full';        // 策略4：全量回归

/**
 * 测试文档
 */
export interface TestDocument {
  module: string;
  version: string;
  testCases: TestCase[];
}

/**
 * 测试用例
 */
export interface TestCase {
  testId: string;
  scenarioNumber: string;
  title: string;
  priority: TestPriority;
  preconditions: string[];
  steps: TestStep[];
  assertions: TestAssertion[];
  testData: Record<string, any>;
  estimatedDuration?: number;
  retryCount?: number;
  tags?: string[];
}

/**
 * 测试步骤
 */
export interface TestStep {
  stepNumber: number;
  description: string;
  action: 'navigate' | 'click' | 'fill' | 'select' | 'wait' | 'hover' | 'press';
  target?: string;
  selector?: string;
  value?: string;
  timeout?: number;
  waitStrategy?: 'load' | 'domcontentloaded' | 'networkidle';
  waitState?: 'attached' | 'detached' | 'visible' | 'hidden';
}

/**
 * 测试断言
 */
export interface TestAssertion {
  type: 'url' | 'visible' | 'text' | 'count' | 'attribute' | 'enabled' | 'disabled';
  description: string;
  selector?: string;
  attribute?: string;
  expected: any;
  category?: 'arrival' | 'stable' | 'success' | 'validation';
}

/**
 * 测试结果
 */
export interface TestResult {
  testId: string;
  title: string;
  priority: TestPriority;
  status: TestStatus;
  startTime: string;
  endTime?: string;
  duration: number;
  assertions: AssertionResult[];
  error?: TestError;
  artifacts: TestArtifacts;
  retryAttempt?: number;
}

/**
 * 断言结果
 */
export interface AssertionResult {
  type: string;
  description: string;
  passed: boolean;
  actual: any;
  expected: any;
}

/**
 * 测试错误
 */
export interface TestError {
  message: string;
  stack?: string;
  failedStep?: string;
  screenshot?: string;
}

/**
 * 测试资产
 */
export interface TestArtifacts {
  screenshots: string[];
  videos: string[];
  traces: string[];
  logs: string[];
  domSnapshots?: string[];
  harLogs?: string[];
}

/**
 * 执行上下文
 */
export interface ExecutionContext {
  module: string;
  environment: 'development' | 'test' | 'staging' | 'production';
  browser: 'chromium' | 'firefox' | 'webkit';
  headless: boolean;
  baseUrl: string;
  storageState?: string;
  outputDir: string;
}

/**
 * 执行选项
 */
export interface ExecutionOptions extends Partial<ExecutionContext> {
  module: string;
  mcpConfig?: MCPConfig;
  parallel?: number;
  retryCount?: number;
  timeout?: number;
}

/**
 * MCP配置
 */
export interface MCPConfig {
  command: string;
  args: string[];
  browser?: string;
  headless?: boolean;
  saveTrace?: boolean;
  saveVideo?: boolean | string;
  saveSession?: boolean;
  testIdAttribute?: string;
}

/**
 * AI分析结果
 */
export interface AIAnalysisResult {
  analysisId: string;
  timestamp: string;
  testResult: TestResult;
  problemCategory: ProblemCategory;
  confidenceScore: number;
  rootCause: RootCauseAnalysis;
  fixLevel: FixLevel;
  suggestedFix?: SuggestedFix;
  regressionStrategy: RegressionStrategy;
  documentSyncNeeded: boolean;
  suggestedDocUpdates?: DocumentUpdate[];
}

/**
 * 根本原因分析
 */
export interface RootCauseAnalysis {
  description: string;
  affectedFiles: string[];
  affectedTests: string[];
  affectedFeatures: string[];
  timeline?: TimelineEvent[];
}

/**
 * 时间线事件
 */
export interface TimelineEvent {
  timestamp: string;
  event: string;
  commit?: string;
  author?: string;
}

/**
 * 修复建议
 */
export interface SuggestedFix {
  fixType: string;
  autoFixable: boolean;
  changes: FileChange[];
  commitMessage: string;
  verificationSteps: string[];
  riskLevel: 'low' | 'medium' | 'high';
}

/**
 * 文件变更
 */
export interface FileChange {
  filePath: string;
  lineNumber?: number;
  oldContent: string;
  newContent: string;
  changeType: 'add' | 'modify' | 'delete';
}

/**
 * 文档更新
 */
export interface DocumentUpdate {
  documentPath: string;
  section: string;
  updateType: 'add' | 'modify' | 'delete';
  oldContent?: string;
  newContent: string;
  reason: string;
}

/**
 * 测试报告
 */
export interface TestReport {
  reportId: string;
  timestamp: string;
  context: ExecutionContext;
  summary: TestSummary;
  results: TestResult[];
  aiAnalyses: AIAnalysisResult[];
  documentSyncCheck: DocumentSyncCheck;
  performance: PerformanceMetrics;
  coverage: CoverageMetrics;
  nextActions: NextAction[];
  artifacts: ReportArtifacts;
}

/**
 * 测试摘要
 */
export interface TestSummary {
  totalTests: number;
  passedTests: number;
  failedTests: number;
  skippedTests: number;
  duration: number;
  overallStatus: 'passed' | 'failed' | 'partial';
  passRate: number;
  priorityDistribution: {
    [key in TestPriority]: {
      total: number;
      passed: number;
      failed: number;
      skipped: number;
      passRate: number;
    };
  };
}

/**
 * 文档同步检查
 */
export interface DocumentSyncCheck {
  status: 'consistent' | 'inconsistent' | 'warning';
  checks: {
    type: string;
    status: 'ok' | 'warning' | 'error';
    details: string;
  }[];
  suggestedUpdates: DocumentUpdate[];
}

/**
 * 性能指标
 */
export interface PerformanceMetrics {
  pageLoadTimes: {
    page: string;
    loadTime: number;
    target: number;
    status: 'ok' | 'warning' | 'error';
  }[];
  apiResponseTimes: {
    api: string;
    responseTime: number;
    target: number;
    status: 'ok' | 'warning' | 'error';
  }[];
  averageTestDuration: number;
}

/**
 * 覆盖率指标
 */
export interface CoverageMetrics {
  functionalCoverage: {
    module: string;
    coverage: number;
    testCount: number;
    status: 'ok' | 'warning' | 'error';
  }[];
  p0Coverage: {
    total: number;
    passed: number;
    passRate: number;
    target: number;
    status: 'ok' | 'warning' | 'error';
  };
}

/**
 * 后续行动
 */
export interface NextAction {
  type: 'auto' | 'manual' | 'suggestion';
  priority: 'immediate' | 'high' | 'medium' | 'low';
  description: string;
  assignee?: 'ai' | 'human';
  status: 'pending' | 'in_progress' | 'completed';
  relatedTestIds?: string[];
}

/**
 * 报告资产
 */
export interface ReportArtifacts {
  reportPath: string;
  screenshotsDir: string;
  videosDir: string;
  tracesDir: string;
  logsDir: string;
  rawDataPath: string;
}

/**
 * 修复模式
 */
export interface FixPattern {
  patternId: string;
  name: string;
  description: string;
  problemCategory: ProblemCategory;
  fixLevel: FixLevel;
  matchConditions: {
    errorMessagePattern?: RegExp;
    affectedFilesPattern?: RegExp;
    codePattern?: RegExp;
  };
  fixTemplate: {
    filePattern: string;
    searchPattern: string | RegExp;
    replaceTemplate: string;
  };
  examples: {
    before: string;
    after: string;
  }[];
  riskLevel: 'low' | 'medium' | 'high';
  verificationSteps: string[];
}

/**
 * 回归测试计划
 */
export interface RegressionPlan {
  strategy: RegressionStrategy;
  testIds: string[];
  estimatedDuration: number;
  parallel: number;
  reason: string;
}
