import axios from "axios";

const client = axios.create({
  baseURL: "/api/v1",
  timeout: 15000
});

export async function overview() {
  const { data } = await client.get("/stats/overview");
  return data.data;
}

export async function tasks() {
  const { data } = await client.get("/inspection/tasks");
  return data.data.tasks;
}

export async function createInspectionTask(payload: Record<string, unknown>) {
  const { data } = await client.post("/inspection/tasks", payload);
  return data.data;
}

export async function cancelInspectionTask(taskId: string) {
  const { data } = await client.post(`/inspection/tasks/${taskId}/cancel`, {});
  return data.data;
}

export async function updateMissionStatus(taskId: string, status = "flying") {
  const { data } = await client.post("/uav/callbacks/mission-status", {
    task_id: taskId,
    vendor: "DJI",
    vendor_mission_id: `mission-${taskId}`,
    status,
    uav_id: "UAV-01",
    timestamp: new Date().toISOString(),
    position: { longitude: 116.1, latitude: 39.1 }
  });
  return data.data;
}

export async function resources() {
  const { data } = await client.get("/inspection/resources");
  return data.data.resources;
}

export async function analysisJobs() {
  const { data } = await client.get("/analysis/jobs");
  return data.data.jobs;
}

export async function analysisResults() {
  const { data } = await client.get("/analysis/results");
  return data.data.results;
}

export async function runAnalysisJob(jobId: string) {
  const { data } = await client.post(`/analysis/jobs/${jobId}/run`, {});
  return data.data;
}

export async function alarms(includeSuppressed = false) {
  const { data } = await client.get("/alarms", { params: { includeSuppressed } });
  return data.data.alarms;
}

export async function decideAlarm(alarmId: string, action: "confirm" | "suppress" | "reopen", reason = "") {
  const { data } = await client.post(`/alarms/${alarmId}/decision`, {
    action,
    reason,
    operator: "告警研判人员"
  });
  return data.data;
}

export async function workorders() {
  const { data } = await client.get("/workorders");
  return data.data.workorders;
}

export async function closeWorkorder(alarmId: string) {
  const { data } = await client.post("/workorders/callbacks/status", {
    alarm_id: alarmId,
    status: "closed",
    result: "现场处置完成",
    comment: "前端闭环确认",
    operator: "巡检平台"
  });
  return data.data;
}

export async function models() {
  const { data } = await client.get("/models");
  return data.data.models;
}

export async function samples() {
  const { data } = await client.get("/samples");
  return data.data.samples;
}

export async function platformEvents() {
  const { data } = await client.get("/platform/events");
  return data.data.events;
}

export async function demoRuns() {
  const { data } = await client.get("/demo/runs");
  return data.data.runs;
}

export async function serviceHealth() {
  const { data } = await axios.get("/actuator/health", { timeout: 10000 });
  return data;
}

export async function aiRuntimeStatus() {
  const { data } = await client.get("/operations/ai-runtime");
  return data.data;
}

export async function modelArtifactRuntimeOverview() {
  const { data } = await client.get("/model-artifacts/runtime-overview", { timeout: 45000 });
  return data.data;
}

export async function uploadModelArtifact(
  deploymentId: string,
  files: { primary: File; secondary?: File; labels: File },
  onProgress?: (percent: number) => void
) {
  const form = new FormData();
  form.append("primary", files.primary);
  if (files.secondary) form.append("secondary", files.secondary);
  form.append("labels", files.labels);
  const { data } = await client.post(`/model-runtime-deployments/${deploymentId}/artifacts`, form, {
    params: { operator: "模型运维管理员" },
    timeout: 60 * 60 * 1000,
    onUploadProgress: (event) => onProgress?.(event.total ? Math.round(event.loaded * 100 / event.total) : 0)
  });
  return data.data;
}

export async function installModelArtifact(deploymentId: string, artifactId: string, approvalTicket: string, loadAfterInstall: boolean) {
  const { data } = await client.post(`/model-runtime-deployments/${deploymentId}/installations`, {
    artifact_id: artifactId,
    approval_ticket: approvalTicket || undefined,
    load_after_install: loadAfterInstall,
    operator: "模型运维管理员",
    reason: "通过系统运维页面安装模型制品",
    idempotency_key: `install-${deploymentId}-${artifactId}-${Date.now()}`
  });
  return data.data;
}

export async function loadModelArtifact(installationId: string) {
  const { data } = await client.post(`/model-artifact-installations/${installationId}/load`, {
    operator: "模型运维管理员",
    reason: "通过系统运维页面加载模型"
  });
  return data.data;
}

export async function unloadModelArtifact(installationId: string) {
  const { data } = await client.post(`/model-artifact-installations/${installationId}/unload`, {
    operator: "模型运维管理员",
    reason: "通过系统运维页面释放模型"
  });
  return data.data;
}

export async function modelArtifactUninstallImpact(installationId: string) {
  const { data } = await client.get(`/model-artifact-installations/${installationId}/uninstall-impact`);
  return data.data;
}

export async function uninstallModelArtifact(installationId: string, reason: string) {
  const { data } = await client.delete(`/model-artifact-installations/${installationId}`, {
    params: { operator: "模型运维管理员", reason }
  });
  return data.data;
}

export async function modelArtifactJob(jobId: string) {
  const { data } = await client.get(`/model-artifact-jobs/${jobId}`);
  return data.data;
}

export async function runDemo() {
  const { data } = await client.post("/demo/run-full-chain", {});
  return data.data;
}

export async function startDemoRun() {
  const { data } = await client.post("/demo/runs", {});
  return data.data;
}

export async function demoRunSnapshot(runId: string) {
  const { data } = await client.get(`/demo/runs/${runId}`);
  return data.data;
}

export async function cancelDemoRun(runId: string) {
  const { data } = await client.post(`/demo/runs/${runId}/cancel`, {});
  return data.data;
}

export async function demoStepSnapshot(runId: string, stepKey: string) {
  const { data } = await client.get(`/demo/runs/${runId}/steps/${encodeURIComponent(stepKey)}`);
  return data.data;
}

export async function retryDemoStep(runId: string, stepKey: string, expectedAttempt = 1) {
  const { data } = await client.post(`/demo/runs/${runId}/steps/${encodeURIComponent(stepKey)}/retry`, {
    reason: "节点异常恢复",
    operator: "巡检平台",
    expected_attempt: expectedAttempt,
    idempotency_key: `${runId}-${stepKey}-${expectedAttempt + 1}`
  });
  return data.data;
}

export async function demoRunEntities(runId: string) {
  const { data } = await client.get(`/demo/runs/${runId}/entities`);
  return data.data;
}

export function demoRunExportUrl(runId: string) {
  return `/api/v1/demo/runs/${runId}/export`;
}

export async function resourcePreview(resourceId: string) {
  const { data } = await client.get(`/inspection/resources/${resourceId}/preview`);
  return data.data;
}

export async function resultEvidence(resultId: string) {
  const { data } = await client.get(`/analysis/results/${resultId}/evidence`);
  return data.data;
}

export async function alarmEvidence(alarmId: string) {
  const { data } = await client.get(`/alarms/${alarmId}/evidence-chain`);
  return data.data;
}

export async function redispatchWorkorder(workorderId: string, assignee = "专业复核人员") {
  const { data } = await client.post(`/workorders/${workorderId}/redispatch`, {
    assignee,
    reason: "运行工作台重新派发",
    operator: "巡检平台"
  });
  return data.data;
}

export async function reviewWorkorder(workorderId: string, action: "approve" | "return") {
  const { data } = await client.post(`/workorders/${workorderId}/review`, {
    action,
    result: action === "approve" ? "复核通过" : "退回重办",
    comment: action === "approve" ? "处置材料完整，确认闭环" : "处置材料需要补充",
    operator: "复核人员"
  });
  return data.data;
}

export async function decideSample(sampleId: string, decision: "accepted" | "excluded", priority = "normal") {
  const { data } = await client.post(`/samples/${sampleId}/decision`, {
    decision,
    priority,
    reason: decision === "accepted" ? "进入标注队列" : "不满足入池要求",
    operator: "算法数据管理员"
  });
  return data.data;
}

export function demoEventsUrl(runId: string) {
  return `/api/v1/demo/runs/${runId}/events`;
}

export async function modelGroups(params: Record<string, unknown> = {}) {
  const { data } = await client.get("/models", { params });
  return data.data.models;
}

export async function modelDetail(modelGroupId: string) {
  const { data } = await client.get(`/models/${modelGroupId}`);
  return data.data;
}

export async function modelVersions(modelGroupId: string) {
  const { data } = await client.get(`/models/${modelGroupId}/versions`);
  return data.data.versions;
}

export async function modelArtifacts(versionId: string) {
  const { data } = await client.get(`/model-versions/${versionId}/artifacts`);
  return data.data.artifacts;
}

export async function validateModelArtifact(versionId: string) {
  const { data } = await client.post(`/model-versions/${versionId}/validate`, { operator: "算法工程师" });
  return data.data;
}

export async function modelRuntimeDeployments(modelGroupId: string) {
  const { data } = await client.get(`/models/${modelGroupId}/runtime-deployments`);
  return data.data.deployments;
}

export async function createModelRuntimeDeployment(modelGroupId: string, payload: Record<string, unknown>) {
  const { data } = await client.post(`/models/${modelGroupId}/runtime-deployments`, payload);
  return data.data;
}

export async function updateModelRuntimeDeployment(deploymentId: string, payload: Record<string, unknown>) {
  const { data } = await client.put(`/model-runtime-deployments/${deploymentId}`, payload);
  return data.data;
}

export async function deleteModelRuntimeDeployment(deploymentId: string) {
  const { data } = await client.delete(`/model-runtime-deployments/${deploymentId}`, { params: { operator: "模型运维管理员" } });
  return data.data;
}

export async function checkModelRuntimeDeployment(deploymentId: string) {
  const { data } = await client.post(`/model-runtime-deployments/${deploymentId}/health-check`, {}, { timeout: 45000 });
  return data.data;
}

export async function checkModelRuntimeConnectivity(deploymentId: string) {
  const { data } = await client.post(`/model-runtime-deployments/${deploymentId}/connectivity-check`, {}, { timeout: 45000 });
  return data.data;
}

export async function activateModelRuntimeDeployment(deploymentId: string, force = false) {
  const { data } = await client.post(`/model-runtime-deployments/${deploymentId}/activate`, {
    force,
    operator: "模型运维管理员",
    reason: "通过模型管理页面切换运行配置"
  }, { timeout: 45000 });
  return data.data;
}

export async function modelParameterSchema(versionId: string) {
  const { data } = await client.get(`/model-versions/${versionId}/parameter-schema`);
  return data.data;
}

export async function modelParameterProfiles(modelGroupId: string) {
  const { data } = await client.get(`/models/${modelGroupId}/parameter-profiles`);
  return data.data.profiles;
}

export async function createModelParameterProfile(modelGroupId: string, payload: Record<string, unknown>) {
  const { data } = await client.post(`/models/${modelGroupId}/parameter-profiles`, payload);
  return data.data;
}

export async function createModelParameterRevision(profileId: string, payload: Record<string, unknown>) {
  const { data } = await client.post(`/parameter-profiles/${profileId}/revisions`, payload);
  return data.data;
}

export async function validateModelParameters(payload: Record<string, unknown>) {
  const { data } = await client.post("/parameter-profiles/validate", payload);
  return data.data;
}

export async function compareModelParameterProfiles(profileIds: string[]) {
  const { data } = await client.get("/parameter-profiles/compare", { params: { profileIds: profileIds.join(",") } });
  return data.data;
}

export async function changeModelParameterProfileStatus(profileId: string, active: boolean) {
  const { data } = await client.post(`/parameter-profiles/${profileId}/${active ? "activate" : "deactivate"}`, { operator: "算法工程师" });
  return data.data;
}

export async function modelTestSamples(params: Record<string, unknown>) {
  const { data } = await client.get("/model-test-samples", { params });
  return data.data.samples;
}

export async function modelSampleSets(modelGroupId: string) {
  const { data } = await client.get(`/models/${modelGroupId}/sample-sets`);
  return data.data.sample_sets;
}

export async function previewModelSampleSet(sampleIds: string[]) {
  const { data } = await client.post("/sample-sets/preview", { sample_ids: sampleIds });
  return data.data;
}

export async function createTestUploadSession(modelGroupId: string) {
  const { data } = await client.post("/test-uploads", { model_group_id: modelGroupId, retention_days: 7, operator: "测试人员" });
  return data.data;
}

export async function uploadTestFiles(sessionId: string, files: File[], onProgress?: (percent: number) => void) {
  const form = new FormData();
  files.forEach((file) => form.append("files", file));
  const { data } = await client.post(`/test-uploads/${sessionId}/files`, form, {
    timeout: 10 * 60 * 1000,
    onUploadProgress: (event) => onProgress?.(event.total ? Math.round(event.loaded * 100 / event.total) : 0)
  });
  return data.data;
}

export async function createChunkedTestFile(sessionId: string, file: File, partSizeBytes: number) {
  const { data } = await client.post(`/test-uploads/${sessionId}/chunked-files`, {
    file_name: file.name,
    content_type: file.type || "application/octet-stream",
    total_size_bytes: file.size,
    part_size_bytes: partSizeBytes
  });
  return data.data;
}

export async function uploadTestFilePart(sessionId: string, manifestId: string, partIndex: number, chunk: Blob) {
  const form = new FormData();
  form.append("chunk", chunk, `part-${partIndex}`);
  const { data } = await client.put(`/test-uploads/${sessionId}/chunked-files/${manifestId}/parts/${partIndex}`, form, {
    timeout: 10 * 60 * 1000
  });
  return data.data;
}

export async function completeChunkedTestFile(sessionId: string, manifestId: string) {
  const { data } = await client.post(`/test-uploads/${sessionId}/chunked-files/${manifestId}/complete`, {});
  return data.data;
}

export async function completeTestUploadSession(sessionId: string) {
  const { data } = await client.post(`/test-uploads/${sessionId}/complete`, {});
  return data.data;
}

export async function deleteTestUploadSession(sessionId: string) {
  const { data } = await client.delete(`/test-uploads/${sessionId}`);
  return data.data;
}

export async function createModelTest(payload: Record<string, unknown>) {
  const { data } = await client.post("/model-tests", payload);
  return data.data;
}

export async function modelTests(params: Record<string, unknown> = {}) {
  const { data } = await client.get("/model-tests", { params });
  return data.data.tests;
}

export async function modelTestDetail(taskId: string) {
  const { data } = await client.get(`/model-tests/${taskId}`);
  return data.data;
}

export async function validateModelTest(taskId: string) {
  const { data } = await client.post(`/model-tests/${taskId}/validate`, {});
  return data.data;
}

export async function startModelTest(taskId: string) {
  const { data } = await client.post(`/model-tests/${taskId}/start`, {});
  return data.data;
}

export async function cancelModelTest(taskId: string) {
  const { data } = await client.post(`/model-tests/${taskId}/cancel`, {});
  return data.data;
}

export async function cloneModelTest(taskId: string) {
  const { data } = await client.post(`/model-tests/${taskId}/clone`, { operator: "测试人员" });
  return data.data;
}

export async function modelTestResults(taskId: string) {
  const { data } = await client.get(`/model-tests/${taskId}/results`);
  return data.data.results;
}

export async function modelTestSummaries(taskId: string) {
  const { data } = await client.get(`/model-tests/${taskId}/summary`);
  return data.data.summaries;
}

export async function modelTestReport(taskId: string) {
  const response = await client.get(`/model-tests/${taskId}/report`, { responseType: "blob" });
  return response.data as Blob;
}

export async function compareModelTests(taskIds: string[]) {
  const { data } = await client.get("/model-tests/compare", { params: { taskIds: taskIds.join(",") } });
  return data.data;
}

export async function submitModelTestFeedback(resultId: string, feedbackType: string, archiveAsSample: boolean, comment = "") {
  const { data } = await client.post(`/model-test-results/${resultId}/feedback`, {
    feedback_type: feedbackType,
    archive_as_sample: archiveAsSample,
    comment,
    operator: "算法数据管理员"
  });
  return data.data;
}

export function modelTestEventsUrl(taskId: string, afterSequence = 0) {
  return `/api/v1/model-tests/${taskId}/events?afterSequence=${afterSequence}`;
}

export async function modelReleases(modelGroupId?: string) {
  const { data } = await client.get("/model-releases", { params: modelGroupId ? { modelGroupId } : {} });
  return data.data.releases;
}

export async function createModelRelease(payload: Record<string, unknown>) {
  const { data } = await client.post("/model-releases", payload);
  return data.data;
}

export async function decideModelRelease(releaseId: string, action: "approve" | "reject" | "promote", comment: string) {
  const { data } = await client.post(`/model-releases/${releaseId}/${action}`, { operator: "发布审批人", comment });
  return data.data;
}

export async function updateModelReleaseGray(releaseId: string, grayPercent: number, strategy: Record<string, unknown>) {
  const { data } = await client.post(`/model-releases/${releaseId}/gray`, {
    gray_percent: grayPercent,
    strategy,
    operator: "发布审批人",
    comment: `调整灰度比例至 ${grayPercent}%`
  });
  return data.data;
}

export async function rollbackModelRelease(releaseId: string, targetVersionId: string, targetProfileId: string, comment: string) {
  const { data } = await client.post(`/model-releases/${releaseId}/rollback`, {
    target_version_id: targetVersionId,
    target_profile_id: targetProfileId,
    operator: "发布审批人",
    comment
  });
  return data.data;
}

export async function modelAuditLogs(params: Record<string, unknown> = {}) {
  const { data } = await client.get("/model-audit-logs", { params });
  return data.data.logs;
}

export async function capabilityCompletion() {
  const { data } = await client.get("/capabilities/completion");
  return data.data;
}

export async function inspectionPlans() {
  const { data } = await client.get("/inspection/plans");
  return data.data.plans;
}

export async function createInspectionPlan(payload: Record<string, unknown>) {
  const { data } = await client.post("/inspection/plans", payload);
  return data.data;
}

export async function activateInspectionPlan(planId: string) {
  const { data } = await client.post(`/inspection/plans/${planId}/activate`, {});
  return data.data;
}

export async function generatePlanTasks(planId: string) {
  const { data } = await client.post(`/inspection/plans/${planId}/generate-tasks`, {});
  return data.data;
}

export async function inspectionObjects() {
  const { data } = await client.get("/inspection/objects");
  return data.data.objects;
}

export async function createInspectionObject(payload: Record<string, unknown>) {
  const { data } = await client.post("/inspection/objects", payload);
  return data.data;
}

export async function inspectionRoutes() {
  const { data } = await client.get("/routes");
  return data.data.routes;
}

export async function createInspectionRoute(payload: Record<string, unknown>) {
  const { data } = await client.post("/routes", payload);
  return data.data;
}

export async function validateRouteVersion(versionId: string) {
  const { data } = await client.post(`/route-versions/${versionId}/validate`, {});
  return data.data;
}

export async function publishRouteVersion(versionId: string) {
  const { data } = await client.post(`/route-versions/${versionId}/publish`, {}, { params: { approvedBy: "user-dispatcher" } });
  return data.data;
}

export async function uavConnections() {
  const { data } = await client.get("/uav/connections");
  return data.data.connections;
}

export async function checkUavConnection(connectionId: string) {
  const { data } = await client.post(`/uav/connections/${connectionId}/check`, {});
  return data.data;
}

export async function synchronizeUavDevices(connectionId: string) {
  const { data } = await client.post(`/uav/connections/${connectionId}/sync-devices`, {});
  return data.data;
}

export async function uavDevices() {
  const { data } = await client.get("/uav/devices");
  return data.data.devices;
}

export async function uavMissions() {
  const { data } = await client.get("/uav/missions");
  return data.data.missions;
}

export async function dispatchUavMission(payload: Record<string, unknown>) {
  const { data } = await client.post("/uav/missions", payload);
  return data.data;
}

export async function executeUavMissionCommand(missionId: string, command: string, expectedMissionVersion?: number) {
  const { data } = await client.post(`/uav/missions/${missionId}/commands`, {
    command,
    requested_by: "user-dispatcher",
    reason: "运行工作台操作",
    expected_mission_version: expectedMissionVersion,
    idempotency_key: `${command}-${missionId}-${Date.now()}`,
    parameters: {}
  });
  return data.data;
}

export async function uavMissionTelemetry(missionId: string) {
  const { data } = await client.get(`/uav/missions/${missionId}/telemetry`);
  return data.data.telemetry;
}

export async function gisFeatures() {
  const { data } = await client.get("/gis/features");
  return data.data;
}

export async function uploadInspectionFile(taskId: string, file: File, resourceType: string, onProgress?: (percent: number) => void) {
  const partSize = 8 * 1024 * 1024;
  const { data: sessionResponse } = await client.post("/uploads", {
    task_id: taskId,
    resource_type: resourceType,
    file_name: file.name,
    content_type: file.type || "application/octet-stream",
    total_size_bytes: file.size,
    part_size_bytes: partSize,
    created_by: "数据接入人员"
  });
  const session = sessionResponse.data;
  for (let partNo = 0; partNo < session.total_parts; partNo += 1) {
    const form = new FormData();
    form.append("chunk", file.slice(partNo * partSize, Math.min(file.size, (partNo + 1) * partSize)), `${file.name}.part-${partNo}`);
    await client.put(`/uploads/${session.upload_session_id}/parts/${partNo}`, form, { timeout: 10 * 60 * 1000 });
    onProgress?.(Math.round(((partNo + 1) / session.total_parts) * 90));
  }
  const { data } = await client.post(`/uploads/${session.upload_session_id}/complete`, {});
  onProgress?.(100);
  return data.data;
}

export async function preprocessJobs() {
  const { data } = await client.get("/preprocess/jobs");
  return data.data.jobs;
}

export async function runPreprocessJob(jobId: string) {
  const { data } = await client.post(`/preprocess/jobs/${jobId}/run`, {});
  return data.data;
}

export async function organizations() {
  const { data } = await client.get("/organizations");
  return data.data.organizations;
}

export async function responsibilityRules() {
  const { data } = await client.get("/responsibility-rules");
  return data.data.rules;
}

export async function notificationDeliveries(status?: string) {
  const { data } = await client.get("/notifications", { params: status ? { status } : {} });
  return data.data.notifications;
}

export async function readNotificationDelivery(notificationId: string) {
  const { data } = await client.post(`/notifications/${notificationId}/read`, {});
  return data.data;
}

export async function executeWorkorderAction(workorderId: string, action: string, result = "", comment = "") {
  const { data } = await client.post(`/workorders/${workorderId}/actions`, {
    action,
    operator_id: "user-field",
    operator_name: action === "APPROVE" || action === "RETURN" ? "专业复核人员" : "现场处置人员",
    result,
    comment,
    metadata: {}
  });
  return data.data;
}

export async function workorderActions(workorderId: string) {
  const { data } = await client.get(`/workorders/${workorderId}/actions`);
  return data.data.actions;
}

export async function workorderEvidence(workorderId: string) {
  const { data } = await client.get(`/workorders/${workorderId}/attachments`);
  return data.data.attachments;
}

export async function uploadWorkorderEvidence(workorderId: string, phase: string, file: File) {
  const form = new FormData();
  form.append("file", file);
  const { data } = await client.post(`/workorders/${workorderId}/attachments`, form, {
    params: { phase, uploadedBy: "现场处置人员", captureTime: new Date().toISOString() },
    timeout: 10 * 60 * 1000
  });
  return data.data;
}

export function workorderEvidenceUrl(attachmentId: string) {
  return `/api/v1/workorder-attachments/${attachmentId}/content`;
}

export async function createReinspection(workorderId: string, routeId?: string) {
  const { data } = await client.post(`/workorders/${workorderId}/reinspection`, {
    requested_by: "专业复核人员",
    route_id: routeId,
    required_methods: ["UAV_REFLIGHT", "AI_COMPARE"]
  });
  return data.data;
}

export async function archivePackages() {
  const { data } = await client.get("/archive-packages");
  return data.data.archives;
}

export async function createArchivePackage(businessType: "TASK" | "WORKORDER", businessId: string) {
  const { data } = await client.post("/archive-packages", { business_type: businessType, business_id: businessId, created_by: "专业复核人员" });
  return data.data;
}
