package track1

import (
	"strings"

	"github.com/explorer/backend/api/freshness"
)

type bridgeDeliveryMode struct {
	Kind   string
	Reason any
	Scope  any
}

func resolveBridgeDeliveryMode(hasRelays bool, diagnostics *freshness.Diagnostics, txFeed freshness.Completeness) bridgeDeliveryMode {
	if !hasRelays {
		if diagnostics != nil && isStaleTransactionVisibility(diagnostics) {
			return bridgeDeliveryMode{
				Kind:   "mixed",
				Reason: "partial_observability_inputs",
				Scope:  "homepage_summary_only",
			}
		}
		return bridgeDeliveryMode{
			Kind:   "live",
			Reason: nil,
			Scope:  nil,
		}
	}

	if diagnostics != nil && isStaleTransactionVisibility(diagnostics) {
		return bridgeDeliveryMode{
			Kind:   "mixed",
			Reason: "relay_snapshot_only_source",
			Scope:  "bridge_monitoring_and_homepage",
		}
	}

	if txFeed == freshness.CompletenessPartial || txFeed == freshness.CompletenessStale {
		return bridgeDeliveryMode{
			Kind:   "mixed",
			Reason: "partial_observability_inputs",
			Scope:  "bridge_monitoring_and_homepage",
		}
	}

	return bridgeDeliveryMode{
		Kind:   "snapshot",
		Reason: "live_homepage_stream_not_attached",
		Scope:  "relay_monitoring_homepage_card_only",
	}
}

func isStaleTransactionVisibility(diagnostics *freshness.Diagnostics) bool {
	if diagnostics == nil {
		return false
	}
	state := strings.ToLower(strings.TrimSpace(diagnostics.ActivityState))
	switch state {
	case "fresh_head_stale_transaction_visibility", "lagging", "stale_transaction_visibility":
		return true
	default:
		return strings.Contains(state, "stale") && strings.Contains(state, "transaction")
	}
}

func buildBridgeModePayload(now string, resolved bridgeDeliveryMode) map[string]interface{} {
	return map[string]interface{}{
		"kind":        resolved.Kind,
		"updated_at":  now,
		"age_seconds": int64(0),
		"reason":      resolved.Reason,
		"scope":       resolved.Scope,
		"source":      freshness.SourceReported,
		"confidence":  freshness.ConfidenceHigh,
		"provenance":  freshness.ProvenanceMissionFeed,
	}
}
