package com.yaoai.ai.providers.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yaoai.ai.providers.config.ArkProperties;
import com.yaoai.ai.providers.service.SeedreamService;
import com.yaoai.common.exception.BizException;
import com.yaoai.common.exception.ErrorCode;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientResponseException;

import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@ConditionalOnProperty(name = "ai.local-stub.enabled", havingValue = "false", matchIfMissing = true)
public class SeedreamServiceImpl implements SeedreamService {

    private static final String ARK_API_KEY_HINT =
            "未配置火山方舟 API Key，请设置环境变量 VOLCENGINE_ARK_API_KEY，或在 application-local.yml 中配置 volcengine.ark.api-key";
    private static final ObjectMapper JSON = new ObjectMapper();

    private final ArkProperties properties;
    private final RestClient restClient;

    public SeedreamServiceImpl(ArkProperties properties) {
        this.properties = properties;
        SimpleClientHttpRequestFactory rf = new SimpleClientHttpRequestFactory();
        rf.setConnectTimeout(Duration.ofSeconds(10));
        rf.setReadTimeout(Duration.ofMinutes(2));
        this.restClient = RestClient.builder()
                .baseUrl(properties.getBaseUrl())
                .defaultHeader("Content-Type", "application/json")
                .requestFactory(rf)
                .build();
    }

    @Override
    public String generateImage(String prompt) {
        return generateImage(prompt, "2048x2048");
    }

    @Override
    public String generateImage(String prompt, String size) {
        return generateImage(prompt, size, List.of());
    }

    @Override
    public String generateImage(String prompt, String size, List<String> referenceImageUrls) {
        String apiKey = resolveApiKey();
        Map<String, Object> body = new LinkedHashMap<>();
        body.put("model", properties.getImageModel());
        body.put("prompt", prompt);
        body.put("n", 1);
        body.put("size", size);
        body.put("response_format", "url");
        List<String> cleanReferences = referenceImageUrls == null
                ? List.of()
                : referenceImageUrls.stream()
                .filter(url -> url != null && !url.isBlank())
                .map(String::trim)
                .toList();
        if (!cleanReferences.isEmpty()) {
            body.put("image", cleanReferences.size() == 1 ? cleanReferences.get(0) : cleanReferences);
        }

        log.info("Seedream generate image: model={}, size={}, references={}",
                properties.getImageModel(), size, cleanReferences.size());
        try {
            ImageResponse resp = restClient.post()
                    .uri("/images/generations")
                    .header("Authorization", "Bearer " + apiKey)
                    .body(body)
                    .retrieve()
                    .body(ImageResponse.class);

            if (resp == null || resp.getData() == null || resp.getData().isEmpty()) {
                throw new BizException(ErrorCode.INTERNAL_ERROR, "Seedream 返回空结果");
            }
            String url = resp.getData().get(0).getUrl();
            log.info("Seedream image generated: url={}", url);
            return url;
        } catch (RestClientResponseException e) {
            if (e.getStatusCode().value() == 401) {
                throw new BizException(ErrorCode.INTERNAL_ERROR,
                        "图片服务鉴权失败，请检查 VOLCENGINE_ARK_API_KEY 是否正确且仍有效");
            }
            log.error("Seedream generate failed: status={}, body={}", e.getStatusCode(), e.getResponseBodyAsString(), e);
            String providerMessage = extractProviderError(e.getResponseBodyAsString());
            throw new BizException(ErrorCode.INTERNAL_ERROR,
                    "图片生成失败: HTTP " + e.getStatusCode().value()
                            + (providerMessage.isBlank() ? "" : " - " + providerMessage));
        } catch (BizException e) {
            throw e;
        } catch (Exception e) {
            log.error("Seedream generate failed", e);
            throw new BizException(ErrorCode.INTERNAL_ERROR, "图片生成失败: " + e.getMessage());
        }
    }

    @Override
    public String getModelId() {
        return properties.getImageModel();
    }

    @Override
    public String getModelName() {
        return "Seedream 文生图";
    }

    private String resolveApiKey() {
        String apiKey = properties.getApiKey();
        if (apiKey == null || apiKey.isBlank()) {
            throw new BizException(ErrorCode.INTERNAL_ERROR, ARK_API_KEY_HINT);
        }
        String normalized = apiKey.trim();
        if ("your-ark-api-key".equalsIgnoreCase(normalized) || "your_ark_api_key".equalsIgnoreCase(normalized)) {
            throw new BizException(ErrorCode.INTERNAL_ERROR, ARK_API_KEY_HINT);
        }
        return normalized;
    }

    private String extractProviderError(String body) {
        if (body == null || body.isBlank()) {
            return "";
        }
        try {
            JsonNode root = JSON.readTree(body);
            JsonNode message = root.path("error").path("message");
            if (message.isTextual() && !message.asText().isBlank()) {
                return message.asText().trim();
            }
        } catch (Exception ignore) {
            // Fall back to the raw body below when provider response is not JSON.
        }
        String normalized = body.replaceAll("\\s+", " ").trim();
        return normalized.length() > 300 ? normalized.substring(0, 300) + "..." : normalized;
    }

    // ---- internal response models ----

    @Data
    private static class ImageResponse {
        private Long created;
        private List<ImageData> data;
    }

    @Data
    private static class ImageData {
        private String url;
        private String b64Json;
    }
}
