// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"context"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strings"
	"time"

	"wa-assistant/backend/database"
	"wa-assistant/backend/models"
)

const maxAgentImageBytes = 20 << 20

type answerImageSelection struct {
	Source   string `json:"source" jsonschema:"enum=knowledge,enum=product,description=Jenis sumber dari metadata image yang tersedia pada hasil tool"`
	SourceID uint   `json:"source_id" jsonschema:"description=ID sumber gambar yang sudah dibaca pada giliran ini; bukan URL atau path"`
}

type answerImageKey struct{}

// Public recall metadata. Storage paths and source-validation hashes stay private.
type ChatImageReference struct {
	Source   string `json:"source"`
	SourceID uint   `json:"source_id"`
	Title    string `json:"title"`
}

func (r ChatResult) ImageReference() *ChatImageReference {
	if r.imageSnapshot == nil {
		return nil
	}
	return &ChatImageReference{Source: r.imageSnapshot.Selection.Source, SourceID: r.imageSnapshot.Selection.SourceID, Title: r.imageSnapshot.Title}
}

func (r ChatImageReference) SimulationHistoryJSON() string {
	if (r.Source != "knowledge" && r.Source != "product") || r.SourceID == 0 {
		return ""
	}
	raw, _ := json.Marshal(agentImageAttachment{Selection: answerImageSelection{Source: r.Source, SourceID: r.SourceID}, Title: clipContextText(r.Title, 500)})
	return string(raw)
}

// Immutable binding to an uploaded source revision. This never comes from
// model-supplied paths or URLs, and is rechecked immediately before delivery.
type agentImageAttachment struct {
	Selection answerImageSelection `json:"selection"`
	AgentID   uint                 `json:"agent_id"`
	Path      string               `json:"path"`
	Mime      string               `json:"mime"`
	UpdatedAt time.Time            `json:"updated_at"`
	Digest    string               `json:"digest"`
	Title     string               `json:"title"`
}

func availableAgentImage(source string, id uint, path string) *answerImageSelection {
	info, err := os.Stat(path)
	if err != nil || !info.Mode().IsRegular() || info.Size() == 0 || info.Size() > maxAgentImageBytes {
		return nil
	}
	return &answerImageSelection{Source: source, SourceID: id}
}

func readAgentImage(path string) ([]byte, string, error) {
	info, err := os.Stat(path)
	if err != nil || !info.Mode().IsRegular() || info.Size() <= 0 || info.Size() > maxAgentImageBytes {
		return nil, "", fmt.Errorf("lampiran gambar tidak tersedia")
	}
	data, err := os.ReadFile(path)
	if err != nil || len(data) > maxAgentImageBytes {
		return nil, "", fmt.Errorf("lampiran gambar tidak dapat dibaca")
	}
	mime := http.DetectContentType(data)
	if !strings.HasPrefix(mime, "image/") {
		return nil, "", fmt.Errorf("lampiran bukan gambar yang valid")
	}
	return data, mime, nil
}

func (s *agentTurnState) selectAnswerImage(agentID uint, choice *answerImageSelection, sources []models.Knowledge) (*agentImageAttachment, string) {
	if choice == nil {
		return nil, ""
	}
	attachment := &agentImageAttachment{Selection: *choice, AgentID: agentID}
	switch choice.Source {
	case "knowledge":
		for _, source := range sources {
			if source.ID == choice.SourceID {
				attachment.Path, attachment.UpdatedAt, attachment.Title = source.ImagePath, source.UpdatedAt, source.Question
			}
		}
	case "product":
		if product, found := s.productFacts[choice.SourceID]; found {
			attachment.Path, attachment.UpdatedAt, attachment.Title = product.ImagePath, product.UpdatedAt, product.Name
		}
	default:
		return nil, "image_source_unavailable"
	}
	if attachment.Path == "" || choice.SourceID == 0 {
		return nil, "image_source_unavailable"
	}
	data, mime, err := readAgentImage(attachment.Path)
	if err != nil {
		return nil, "image_source_unavailable"
	}
	digest := sha256.Sum256(data)
	attachment.Mime, attachment.Digest = mime, hex.EncodeToString(digest[:])
	return attachment, ""
}

func (image *agentImageAttachment) currentIssue(ctx context.Context, agentID uint) string {
	if image == nil {
		return ""
	}
	if image.AgentID != agentID || image.Selection.SourceID == 0 || database.DB == nil {
		return "image_source_unavailable"
	}
	var path string
	var updated time.Time
	switch image.Selection.Source {
	case "knowledge":
		var row models.Knowledge
		if database.DB.WithContext(ctx).Where("id = ? AND agent_id = ? AND active = ? AND review_status = ?", image.Selection.SourceID, agentID, true, "published").First(&row).Error != nil {
			return "image_source_unavailable"
		}
		if row.EffectiveFrom != nil && row.EffectiveFrom.After(time.Now()) || row.EffectiveUntil != nil && !row.EffectiveUntil.After(time.Now()) {
			return "image_source_unavailable"
		}
		path, updated = row.ImagePath, row.UpdatedAt
	case "product":
		var row models.Product
		if database.DB.WithContext(ctx).Where("id = ? AND agent_id = ?", image.Selection.SourceID, agentID).First(&row).Error != nil {
			return "image_source_unavailable"
		}
		path, updated = row.ImagePath, row.UpdatedAt
	default:
		return "image_source_unavailable"
	}
	if path != image.Path || !updated.Equal(image.UpdatedAt) {
		return "image_source_changed"
	}
	data, mime, err := readAgentImage(path)
	if err != nil {
		return "image_source_unavailable"
	}
	digest := sha256.Sum256(data)
	if mime != image.Mime || hex.EncodeToString(digest[:]) != image.Digest {
		return "image_source_changed"
	}
	return ""
}

func (r ChatResult) ImageSnapshotJSON() string {
	if r.imageSnapshot == nil {
		return ""
	}
	raw, _ := json.Marshal(r.imageSnapshot)
	return string(raw)
}

// Retries use the exact stored bytes and the same still-published revision.
func ValidateAIImageRetry(ctx context.Context, agentID uint, snapshot string, data []byte) error {
	var image agentImageAttachment
	if json.Unmarshal([]byte(snapshot), &image) != nil {
		return fmt.Errorf("referensi lampiran AI tidak valid")
	}
	if issue := image.currentIssue(ctx, agentID); issue != "" {
		return fmt.Errorf("%s", issue)
	}
	digest := sha256.Sum256(data)
	if hex.EncodeToString(digest[:]) != image.Digest {
		return fmt.Errorf("salinan lampiran AI berubah")
	}
	return nil
}
