/**
 * API 服务层
 * 与后端 FastAPI 通信
 */

const API_BASE = 'http://localhost:8080/api';

// 类型定义
export interface Intent {
	id: number;
	title: string;
	content: string | null;
	status: string;
	created_at: string;
	updated_at: string;
}

export interface IntentListResponse {
	total: number;
	items: Intent[];
}

export interface GenerateRequest {
	prompt?: string;
	test_type?: string;
	test_target?: string;
	additional_requirements?: string;
}

export interface GenerateResponse {
	content: string;
	success: boolean;
	error?: string;
}

export interface CheckRequest {
	content: string;
	intent_id?: number;
	requirements?: string[];
}

export interface CheckResult {
	passed: boolean;
	score: number;
	issues: string[];
	suggestions: string[];
}

export interface CheckResponse {
	result: CheckResult;
	record_id?: number;
	success: boolean;
	error?: string;
}

// 提取的步骤参数
export interface ExtractedStep {
	id: number;
	name: string;
	purpose: string;
	deviceParams: {
		[deviceCategory: string]: {
			[paramName: string]: string;
		};
	};
}

export interface ExtractStepsResponse {
	success: boolean;
	steps: ExtractedStep[];
	error?: string;
}

export interface ParseFileResponse {
	filename: string;
	suffix: string;
	title: string;
	content: string;
	raw_result?: unknown;
}

// API 方法
async function request<T>(
	endpoint: string,
	options: RequestInit = {}
): Promise<T> {
	const response = await fetch(`${API_BASE}${endpoint}`, {
		headers: {
			'Content-Type': 'application/json',
			...options.headers,
		},
		...options,
	});

	if (!response.ok) {
		throw new Error(`HTTP error! status: ${response.status}`);
	}

	return response.json();
}

export const apiService = {
	// 意图 CRUD
	async listIntents(skip = 0, limit = 20): Promise<IntentListResponse> {
		return request(`/intent?skip=${skip}&limit=${limit}`);
	},

	async getIntent(id: number): Promise<Intent> {
		return request(`/intent/${id}`);
	},

	async createIntent(data: { title: string; content?: string }): Promise<Intent> {
		return request('/intent', {
			method: 'POST',
			body: JSON.stringify(data),
		});
	},

	async updateIntent(id: number, data: { title?: string; content?: string; status?: string }): Promise<Intent> {
		return request(`/intent/${id}`, {
			method: 'PUT',
			body: JSON.stringify(data),
		});
	},

	async deleteIntent(id: number): Promise<void> {
		await request(`/intent/${id}`, {
			method: 'DELETE',
		});
	},

	// AI 方法
	async generateIntentContent(data: GenerateRequest): Promise<GenerateResponse> {
		return request('/ai/generate-intent', {
			method: 'POST',
			body: JSON.stringify(data),
		});
	},

	async generateTestPlan(requirementText: string, sourceName?: string): Promise<GenerateResponse> {
		return request('/ai/generate-plan', {
			method: 'POST',
			body: JSON.stringify({ 
				requirement_text: requirementText,
				source_name: sourceName || '用户输入'
			}),
		});
	},

	async generateContent(prompt: string, context?: string): Promise<GenerateResponse> {
		return request('/ai/generate', {
			method: 'POST',
			body: JSON.stringify({ prompt, context }),
		});
	},

	async checkContent(data: CheckRequest): Promise<CheckResponse> {
		return request('/ai/check', {
			method: 'POST',
			body: JSON.stringify(data),
		});
	},

	// 从意图编制内容中提取测试步骤和参数
	async extractSteps(content: string, title?: string): Promise<ExtractStepsResponse> {
		return request('/ai/extract-steps', {
			method: 'POST',
			body: JSON.stringify({ 
				content,
				title: title || '意图编制'
			}),
		});
	},

	async parseIntentFile(file: File): Promise<ParseFileResponse> {
		const formData = new FormData();
		formData.append('file', file);

		const response = await fetch(`${API_BASE}/intent/parse-file`, {
			method: 'POST',
			body: formData,
		});

		if (!response.ok) {
			let detail = '';
			try {
				const data = await response.json();
				detail = data?.detail ? `: ${data.detail}` : '';
			} catch {
				// ignore
			}
			throw new Error(`HTTP error! status: ${response.status}${detail}`);
		}

		return response.json();
	},
};

export default apiService;
