package com.adx.tracking.httpapi;

import java.util.List;
import java.util.Map;

/**
 * 对应 Go httpapi.MediaPlacement。
 * 持有百度媒体投放配置（mediaId / appId / tagId / 平台映射）。
 */
public class MediaPlacement {

    private long baiduMediaId;
    private String baiduAppId;
    private String baiduTagId;
    private Map<String, BaiduAppPlacement> platforms; // "android" | "ios"
    private long bidFloor;
    private List<Integer> actionTypes;

    // ─── Getters / Setters ────────────────────────────────────────────────────

    public long getBaiduMediaId() { return baiduMediaId; }
    public void setBaiduMediaId(long v) { this.baiduMediaId = v; }
    public String getBaiduAppId() { return baiduAppId; }
    public void setBaiduAppId(String v) { this.baiduAppId = v; }
    public String getBaiduTagId() { return baiduTagId; }
    public void setBaiduTagId(String v) { this.baiduTagId = v; }
    public Map<String, BaiduAppPlacement> getPlatforms() { return platforms; }
    public void setPlatforms(Map<String, BaiduAppPlacement> v) { this.platforms = v; }
    public long getBidFloor() { return bidFloor; }
    public void setBidFloor(long v) { this.bidFloor = v; }
    public List<Integer> getActionTypes() { return actionTypes; }
    public void setActionTypes(List<Integer> v) { this.actionTypes = v; }

    // ─── resolve() ───────────────────────────────────────────────────────────

    /**
     * 对应 Go MediaPlacement.Resolve()。
     * 优先按 baidu_tag_id/tag_id 查，其次按 platform，最后用默认值。
     */
    public Resolved resolve(Map<String, String> params) {
        String tagId = firstParam(params, "baidu_tag_id", "tag_id", "tagid");
        if (tagId != null && !tagId.isBlank()) {
            Resolved r = resolveByTagId(tagId);
            if (r != null) return r;
            throw new IllegalArgumentException("unknown baidu tag id: " + tagId);
        }

        String platform = normalizePlatform(firstParam(params, "platform", "os", "system", "device_os"));
        if (platform != null && !platform.isBlank()) {
            Resolved r = resolveByPlatform(platform);
            if (r != null) return r;
            throw new IllegalArgumentException("unsupported baidu platform: " + platform);
        }

        if (baiduAppId != null && !baiduAppId.isBlank()
                && baiduTagId != null && !baiduTagId.isBlank()) {
            return new Resolved(null, baiduAppId, baiduTagId);
        }

        if (platforms != null && platforms.size() == 1) {
            String p = platforms.keySet().iterator().next();
            Resolved r = resolveByPlatform(p);
            if (r != null) return r;
        }

        throw new IllegalArgumentException("missing baidu_tag_id or platform");
    }

    private Resolved resolveByTagId(String tagId) {
        if (platforms != null) {
            for (Map.Entry<String, BaiduAppPlacement> e : platforms.entrySet()) {
                BaiduAppPlacement p = e.getValue();
                if (p.getAppId() != null && p.getTagIds() != null && p.getTagIds().contains(tagId)) {
                    return new Resolved(e.getKey(), p.getAppId(), tagId);
                }
            }
        }
        if (baiduAppId != null && tagId.equals(baiduTagId)) {
            return new Resolved(null, baiduAppId, baiduTagId);
        }
        return null;
    }

    private Resolved resolveByPlatform(String platform) {
        if (platforms == null) return null;
        BaiduAppPlacement p = platforms.get(platform);
        if (p == null || p.getAppId() == null || p.getTagIds() == null || p.getTagIds().isEmpty()) {
            return null;
        }
        if (p.getTagIds().size() > 1) {
            throw new IllegalArgumentException(
                    "baidu_tag_id is required for platform " + platform
                    + " because multiple tag ids are configured");
        }
        return new Resolved(platform, p.getAppId(), p.getTagIds().get(0));
    }

    private static String firstParam(Map<String, String> p, String... keys) {
        if (p == null) return null;
        for (String k : keys) {
            String v = p.get(k);
            if (v != null && !v.isBlank()) return v.trim();
        }
        return null;
    }

    static String normalizePlatform(String value) {
        if (value == null) return null;
        return switch (value.toLowerCase().trim()) {
            case "ios", "iphone", "ipad", "1" -> "ios";
            case "android", "安卓", "2" -> "android";
            default -> null;
        };
    }

    // ─── 嵌套类型 ─────────────────────────────────────────────────────────────

    public static class BaiduAppPlacement {
        private String appId;
        private List<String> tagIds;
        public String getAppId() { return appId; }
        public void setAppId(String v) { this.appId = v; }
        public List<String> getTagIds() { return tagIds; }
        public void setTagIds(List<String> v) { this.tagIds = v; }
    }

    /** 解析结果（对应 Go resolvedMediaPlacement） */
    public record Resolved(String platform, String appId, String tagId) {}
}
