package job

import (
	"fmt"
	"strconv"
	"strings"

	missionentity "haixun-backend/internal/model/copy_mission/domain/entity"
	missiondomain "haixun-backend/internal/model/copy_mission/domain/usecase"
)

func intField(payload map[string]any, key string) int {
	if payload == nil {
		return 0
	}
	switch v := payload[key].(type) {
	case int:
		return v
	case int64:
		return int(v)
	case float64:
		return int(v)
	case string:
		n, _ := strconv.Atoi(strings.TrimSpace(v))
		return n
	default:
		return 0
	}
}

func copyMissionIDFromPayload(payload map[string]any) string {
	if id := stringField(payload, "copy_mission_id"); id != "" {
		return id
	}
	return stringField(payload, "mission_id")
}

func similarAccountsFromSummary(items []missiondomain.SimilarAccountSummary) []missionentity.SimilarAccount {
	out := make([]missionentity.SimilarAccount, 0, len(items))
	for _, item := range items {
		username := strings.TrimSpace(strings.TrimPrefix(item.Username, "@"))
		if username == "" {
			continue
		}
		out = append(out, missionentity.SimilarAccount{
			Username:        username,
			Reason:          item.Reason,
			Source:          item.Source,
			MatchedSource:   append([]string(nil), item.MatchedSource...),
			Confidence:      item.Confidence,
			Status:          item.Status,
			TopicRelevance:  item.TopicRelevance,
			LastSeenAt:      item.LastSeenAt,
			ProfileURL:      item.ProfileURL,
			AuthorVerified:  item.AuthorVerified,
			FollowerCount:   item.FollowerCount,
			EngagementScore: item.EngagementScore,
			LikeCount:       item.LikeCount,
			ReplyCount:      item.ReplyCount,
			PostCount:       item.PostCount,
		})
	}
	return out
}

func audienceSamplesFromSummary(items []missiondomain.AudienceSampleSummary) []missionentity.AudienceSample {
	out := make([]missionentity.AudienceSample, 0, len(items))
	for _, item := range items {
		username := strings.TrimSpace(strings.TrimPrefix(item.Username, "@"))
		if username == "" {
			continue
		}
		out = append(out, missionentity.AudienceSample{
			Username:       username,
			SamplePostID:   item.SamplePostID,
			SampleText:     item.SampleText,
			ReplyLikeCount: item.ReplyLikeCount,
			Appearances:    item.Appearances,
			FirstSeenAt:    item.FirstSeenAt,
			LastSeenAt:     item.LastSeenAt,
			Status:         item.Status,
		})
	}
	return out
}

func debugPayloadValue(value any) string {
	return fmt.Sprintf("%v", value)
}
