import { api } from "@/lib/api";
import { RequirementItem, RequirementExtractionResult } from "@/lib/document-mock";

export interface SrsJobCreateResponse {
  job_id: number;
  status: string;
}

export interface SrsJobStatusResponse {
  job_id: number;
  tool_name: string;
  status: "pending" | "processing" | "completed" | "failed";
  error_message?: string | null;
  extraction_id?: number | null;
}

export interface SrsResultResponse {
  jobId: number;
  documentName: string;
  generatedAt: string;
  statistics: Record<string, unknown>;
  requirements: RequirementItem[];
  rawOutput: Record<string, unknown>;
}

export interface SrsHistoryItem {
  jobId: number;
  documentName: string;
  generatedAt: string;
  totalRequirements: number;
  status: string;
  createdAt: string;
  updatedAt: string;
}

export interface KnowledgeBaseSummary {
  id: number;
  name: string;
  description?: string | null;
}

export interface TestingPipelineItem {
  id: string;
  content: string;
}

export interface TestingPipelineCase {
  id: string;
  item_id: string;
  operation_steps: string[];
  test_content: string;
  expected_result_placeholder: string;
}

export interface TestingPipelineExpectedResult {
  id: string;
  case_id: string;
  result: string;
}

export interface TestingPipelineResponse {
  trace_id: string;
  requirement_type: string;
  reason: string;
  candidates: string[];
  test_items: Record<string, TestingPipelineItem[]>;
  test_cases: Record<string, TestingPipelineCase[]>;
  expected_results: Record<string, TestingPipelineExpectedResult[]>;
  formatted_output: string;
  pipeline_summary: string;
  knowledge_used: boolean;
}

export interface TestingGenerationSaveRequest {
  source_job_id?: number;
  source_document_name: string;
  knowledge_base_id?: number;
  generated_file: Record<string, unknown>;
}

export interface TestingGenerationJobCreateRequest {
  source_job_id?: number;
  source_document_name: string;
  knowledge_base_id?: number;
  requirements: Array<{
    id: string;
    description: string;
    priority: string;
    acceptanceCriteria: string[];
    sourceField: string;
    sectionUid?: string;
    sectionNumber?: string;
    sectionTitle?: string;
    requirementType?: string;
    interfaceName?: string;
    interfaceType?: string;
    dataSource?: string;
    dataDestination?: string;
    sortOrder: number;
  }>;
}

export interface TestingGenerationJobCreateResponse {
  job_id: number;
  status: string;
}

export interface TestingGenerationJobStatusResponse {
  job_id: number;
  tool_name: string;
  status: "pending" | "processing" | "completed" | "failed";
  error_message?: string | null;
  started_at?: string | null;
  completed_at?: string | null;
  source_document_name?: string | null;
  current_step?: number | null;
  total_steps?: number | null;
  current_requirement_id?: string | null;
}

export interface TestingGenerationResult {
  jobId: number;
  sourceJobId?: number | null;
  sourceDocumentName: string;
  generatedAt: string;
  totalRequirements: number;
  knowledgeBaseId?: number | null;
  generatedFile: Record<string, unknown>;
}

export interface TestingGenerationHistoryItem {
  jobId: number;
  sourceJobId?: number | null;
  sourceDocumentName: string;
  generatedAt: string;
  totalRequirements: number;
  knowledgeBaseId?: number | null;
  status: string;
  createdAt: string;
  updatedAt: string;
}

export const createSrsJob = async (file: File): Promise<SrsJobCreateResponse> => {
  const formData = new FormData();
  formData.append("file", file);
  return api.post("/api/tools/srs/jobs", formData) as Promise<SrsJobCreateResponse>;
};

export const getSrsJobStatus = async (
  jobId: number
): Promise<SrsJobStatusResponse> => {
  return api.get(`/api/tools/srs/jobs/${jobId}`) as Promise<SrsJobStatusResponse>;
};

export const getSrsJobResult = async (jobId: number): Promise<SrsResultResponse> => {
  return api.get(`/api/tools/srs/jobs/${jobId}/result`) as Promise<SrsResultResponse>;
};

export const saveSrsRequirements = async (
  jobId: number,
  extraction: RequirementExtractionResult
): Promise<SrsResultResponse> => {
  const requirements = extraction.requirements.map((item, index) => ({
    id: item.id,
    description: item.description,
    priority: item.priority,
    acceptanceCriteria: item.acceptanceCriteria,
    sourceField: item.sourceField,
    sectionUid: item.sectionUid,
    sectionNumber: item.sectionNumber,
    sectionTitle: item.sectionTitle,
    requirementType: item.requirementType,
    interfaceName: item.interfaceName,
    interfaceType: item.interfaceType,
    dataSource: item.dataSource,
    dataDestination: item.dataDestination,
    sortOrder: index,
  }));

  return api.put(`/api/tools/srs/jobs/${jobId}/requirements`, {
    requirements,
  }) as Promise<SrsResultResponse>;
};

export const toExtractionResult = (
  result: SrsResultResponse
): RequirementExtractionResult => {
  return {
    documentName: result.documentName,
    generatedAt: result.generatedAt,
    requirements: result.requirements,
    rawOutput: result.rawOutput,
  };
};

export const listSrsHistory = async (): Promise<SrsHistoryItem[]> => {
  return api.get("/api/tools/srs/history") as Promise<SrsHistoryItem[]>;
};

export const deleteSrsJob = async (jobId: number): Promise<void> => {
  await api.delete(`/api/tools/srs/jobs/${jobId}`);
};

export const listKnowledgeBases = async (): Promise<KnowledgeBaseSummary[]> => {
  return api.get("/api/knowledge-base") as Promise<KnowledgeBaseSummary[]>;
};

export const generateTestingContent = async (
  requirementText: string,
  knowledgeBaseId?: number
): Promise<TestingPipelineResponse> => {
  return api.post("/api/testing/generate", {
    requirement_text: requirementText,
    knowledge_base_ids: knowledgeBaseId ? [knowledgeBaseId] : [],
    use_model_generation: true,
  }) as Promise<TestingPipelineResponse>;
};

export const createTestingGenerationJob = async (
  payload: TestingGenerationJobCreateRequest
): Promise<TestingGenerationJobCreateResponse> => {
  return api.post("/api/tools/testing/jobs", payload) as Promise<TestingGenerationJobCreateResponse>;
};

export const getTestingGenerationJobStatus = async (
  jobId: number
): Promise<TestingGenerationJobStatusResponse> => {
  return api.get(`/api/tools/testing/jobs/${jobId}`) as Promise<TestingGenerationJobStatusResponse>;
};

export const saveTestingGeneration = async (
  payload: TestingGenerationSaveRequest
): Promise<TestingGenerationResult> => {
  return api.post("/api/tools/testing/generations", payload) as Promise<TestingGenerationResult>;
};

export const listTestingHistory = async (): Promise<TestingGenerationHistoryItem[]> => {
  return api.get("/api/tools/testing/history") as Promise<TestingGenerationHistoryItem[]>;
};

export const getTestingGenerationResult = async (
  jobId: number
): Promise<TestingGenerationResult> => {
  return api.get(`/api/tools/testing/jobs/${jobId}/result`) as Promise<TestingGenerationResult>;
};

export const deleteTestingGeneration = async (jobId: number): Promise<void> => {
  await api.delete(`/api/tools/testing/jobs/${jobId}`);
};
