package com.ai.trackwalker.demo;

import com.ai.trackwalker.api.ApiResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;

@RestController
@RequestMapping("/api/v1/demo/runs")
public class DemoRunController {
    private final DemoRunService service;

    public DemoRunController(DemoRunService service) {
        this.service = service;
    }

    @PostMapping
    public ApiResponse<?> startRun() {
        return ApiResponse.ok(service.startRun());
    }

    @GetMapping
    public ApiResponse<?> listRuns() {
        return ApiResponse.ok(Map.of("runs", service.listRuns()));
    }

    @GetMapping("/{runId}")
    public ApiResponse<?> snapshot(@PathVariable String runId) {
        return ApiResponse.ok(service.snapshot(runId));
    }

    @GetMapping("/{runId}/events")
    public SseEmitter events(@PathVariable String runId) {
        return service.subscribe(runId);
    }

    @GetMapping("/{runId}/events/history")
    public ApiResponse<?> history(@PathVariable String runId) {
        return ApiResponse.ok(Map.of("events", service.history(runId)));
    }

    @GetMapping("/{runId}/steps/{stepKey}")
    public ApiResponse<?> stepSnapshot(@PathVariable String runId, @PathVariable String stepKey) {
        return ApiResponse.ok(service.stepSnapshot(runId, stepKey));
    }

    @PostMapping("/{runId}/steps/{stepKey}/retry")
    public ApiResponse<?> retryStep(
            @PathVariable String runId,
            @PathVariable String stepKey,
            @RequestBody(required = false) com.ai.trackwalker.api.dto.Requests.RetryStepRequest request
    ) {
        return ApiResponse.ok(service.retryStep(runId, stepKey, request));
    }

    @GetMapping("/{runId}/entities")
    public ApiResponse<?> entities(@PathVariable String runId) {
        return ApiResponse.ok(service.entities(runId));
    }

    @GetMapping("/{runId}/export")
    public ApiResponse<?> export(@PathVariable String runId) {
        return ApiResponse.ok(service.exportRun(runId));
    }

    @PostMapping("/{runId}/cancel")
    public ApiResponse<?> cancel(@PathVariable String runId) {
        return ApiResponse.ok(service.cancel(runId));
    }
}
