// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/cloudwego/eino/components/tool"
	"github.com/cloudwego/eino/components/tool/utils"
	"regexp"
	"strconv"
	"strings"
	"time"
)

type calculationInput struct {
	ProductID uint                       `json:"product_id,omitempty" jsonschema:"description=ID produk yang sudah dibaca melalui lookup_products; pilih ini atau source_id"`
	SourceID  uint                       `json:"source_id,omitempty" jsonschema:"description=ID pengetahuan yang memuat harga rupiah resmi; pilih ini atau product_id"`
	UnitPrice int64                      `json:"unit_price" jsonschema:"description=Harga satuan rupiah persis dari sumber, tanpa titik/koma"`
	Quantity  int64                      `json:"quantity" jsonschema:"description=Jumlah unit atau peserta yang dinyatakan pelanggan, bukan usia atau kapasitas kamar"`
	Subtract  *calculationDeductionInput `json:"subtract,omitempty" jsonschema:"description=Opsional untuk menghitung sisa dari nominal resmi per unit, misalnya DP. Harus bersumber dari pengetahuan yang sudah dibaca, bukan diskon atau pembayaran rekaan"`
}
type calculationDeductionInput struct {
	SourceID  uint  `json:"source_id" jsonschema:"description=ID pengetahuan yang sudah dibaca dan memuat nominal pengurang per unit serta ketentuannya"`
	UnitPrice int64 `json:"unit_price" jsonschema:"description=Nominal pengurang per unit dalam rupiah persis dari sumber, misalnya DP per peserta; memakai quantity yang sama"`
}
type calculationResult struct {
	UnitPrice         int64  `json:"unit_price"`
	Quantity          int64  `json:"quantity"`
	Subtotal          int64  `json:"subtotal"`
	DeductionSubtotal *int64 `json:"deduction_subtotal,omitempty"`
	Remainder         *int64 `json:"remainder,omitempty"`
	Notice            string `json:"notice"`
}

var rupiahAmountPattern = regexp.MustCompile(`(?i)\brp\.?\s*([0-9][0-9.,]*)(?:\s*(ribu|rb|juta|jt))?\b`)
var rupiahGroupingPattern = regexp.MustCompile(`^[0-9]{1,3}(?:\.[0-9]{3})+$`)

const countWord = `(?:satu|dua|tiga|empat|lima|enam|tujuh|delapan|sembilan|sepuluh|sebelas|belas|puluh|ratus|seratus|ribu|seribu)`
const countQuote = `(?:[0-9]{1,3}|` + countWord + `(?:\s+` + countWord + `){0,7})`

var orderQuantityPattern = regexp.MustCompile(`(?i)\b(` + countQuote + `)\s*(?:pcs|buah|unit|item|paket|lembar|biji)\b|\b(?:jumlah|qty|beli|pesan|ambil|order|jadi|menjadi)\s*[:=]?\s*(` + countQuote + `)\b|\b(` + countQuote + `)\s+yang\b`)

func hasRupiahPrice(source string, price int64) bool {
	for _, match := range rupiahAmountPattern.FindAllStringSubmatch(source, -1) {
		raw := strings.TrimSuffix(strings.TrimRight(match[1], ".,"), ",00")
		if strings.Contains(raw, ",") || (strings.Contains(raw, ".") && !rupiahGroupingPattern.MatchString(raw)) {
			continue
		}
		number := strings.ReplaceAll(raw, ".", "")
		amount, err := strconv.ParseInt(number, 10, 64)
		if err != nil || amount > 1_000_000_000_000 {
			continue
		}
		switch strings.ToLower(match[2]) {
		case "rb", "ribu":
			amount *= 1000
		case "jt", "juta":
			amount *= 1000000
		}
		if amount == price {
			return true
		}
	}
	return false
}
func (s *agentTurnState) hasCustomerQuantity(quantity int64) bool {
	return s.hasCustomerProductQuantity(quantity, 0)
}

func (s *agentTurnState) hasCustomerProductQuantity(quantity int64, productID uint) bool {
	return s.hasCustomerPriceQuantity(quantity, productID, s.productFacts[productID].Price)
}

func (s *agentTurnState) hasCustomerPriceQuantity(quantity int64, productID uint, priceEvidence string) bool {
	latest := s.handoffUserMessage
	if latest == "" {
		latest = s.userMessage
	}
	messages := append(append([]string{}, s.customerMessages...), latest)
	for i := len(messages) - 1; i >= 0; i-- {
		text := strings.ToLower(strings.TrimSpace(messages[i]))
		// A quantity directly beside a verified catalog name needs no unit word
		// (e.g. "dua <product>"). Keep it bound to that product, not another item
		// in the same sentence. Catalog data, never model-supplied names, defines
		// this grammar. A newer count supersedes history even when it mismatches.
		namedQuantity, matchedProduct := false, false
		namedCounts := map[int64]bool{}
		for id, product := range s.productFacts {
			name := strings.TrimSpace(product.Name)
			if name == "" {
				continue
			}
			pattern := regexp.MustCompile(`(?i)\b(` + countQuote + `)\s+(?:(?:pcs|buah|unit|item|paket|lembar|biji)\s+)?` + regexp.QuoteMeta(name) + `\b|\b` + regexp.QuoteMeta(name) + `\s*(?::|=|sebanyak|jumlah)?\s*(` + countQuote + `)\b`)
			for _, match := range pattern.FindAllStringSubmatch(text, -1) {
				for _, value := range match[1:] {
					if n, valid := ParseCustomerCount(value); valid {
						namedQuantity = true
						namedCounts[int64(n)] = true
						if productID == 0 || id == productID {
							matchedProduct = int64(n) == quantity
						}
					}
				}
			}
		}
		if namedQuantity {
			if productID == 0 {
				// A knowledge-only price has no catalog item binding. Multiple
				// different named counts require clarification, not map iteration.
				return len(namedCounts) == 1 && namedCounts[quantity]
			}
			return matchedProduct
		}
		if count, found := customerServiceQuantity(text, priceEvidence); found {
			return count == quantity
		}
		if matches := orderQuantityPattern.FindAllStringSubmatch(text, -1); len(matches) > 0 {
			for _, match := range matches {
				for _, value := range match[1:] {
					if n, valid := ParseCustomerCount(value); valid && int64(n) == quantity {
						return true
					}
				}
			}
			return false // A more recent quantity replaces an earlier one.
		}
	}
	return false
}

// Explicit arithmetic over a checked price and a customer supplied quantity.
// Never accepts an expression, an arbitrary price, or a write/checkout action.
func (s *agentTurnState) calculateTotal(ctx context.Context, agentID uint, in calculationInput) (calculationResult, string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if in.Quantity < 1 || in.Quantity > 999 {
		return calculationResult{}, "Jumlah hitung harus 1–999 dan cocok dengan pesan pelanggan terbaru yang menyebut jumlah. Periksa kaitan jumlah dan produk; tanyakan hanya jika belum jelas."
	}
	if in.UnitPrice < 1 || in.UnitPrice > 1_000_000_000_000 || (in.ProductID == 0) == (in.SourceID == 0) {
		return calculationResult{}, "Pilih satu sumber harga resmi dari hasil tools."
	}
	source := ""
	if in.ProductID != 0 {
		product, ok := s.productFacts[in.ProductID]
		if !ok {
			return calculationResult{}, "Baca produk dengan lookup_products terlebih dahulu."
		}
		if s.productIncomplete[in.ProductID] {
			return calculationResult{}, "Rincian harga produk terpotong. Gunakan read_product dengan product_id untuk membaca syarat lengkap sebelum menghitung."
		}
		if issue := s.freshBusinessFacts(ctx, agentID); issue != "" {
			return calculationResult{}, issue
		}
		source = product.Price
	} else {
		rows, issue := s.freshAnswerSources(ctx, agentID, []uint{in.SourceID})
		if issue != "" {
			return calculationResult{}, issue
		}
		source = rows[0].Answer
	}
	if !hasRupiahPrice(source, in.UnitPrice) {
		return calculationResult{}, "Harga satuan rupiah tidak cocok dengan sumber. Periksa kembali; jangan menebak harga atau mata uang."
	}
	if !s.hasCustomerPriceQuantity(in.Quantity, in.ProductID, source) {
		return calculationResult{}, "Jumlah hitung harus cocok dengan jumlah unit atau peserta pelanggan, sesuai kategori tarif. Usia, tanggal, durasi, dan kapasitas kamar bukan jumlah pesanan. Tanyakan hanya jika jumlah atau kategori belum jelas."
	}
	result := calculationResult{UnitPrice: in.UnitPrice, Quantity: in.Quantity, Subtotal: in.UnitPrice * in.Quantity, Notice: "Hasil perhitungan dari harga resmi dan jumlah pelanggan; syarat serta biaya lain tetap mengikuti sumber. Ini bukan bukti booking, pembayaran diterima, atau diskon disetujui."}
	if in.Subtract != nil {
		deduction := in.Subtract
		if deduction.SourceID == 0 || deduction.UnitPrice < 1 || deduction.UnitPrice > in.UnitPrice {
			return calculationResult{}, "Pengurang harus nominal resmi per unit dari pengetahuan, positif dan tidak melebihi harga per unit."
		}
		rows, issue := s.freshAnswerSources(ctx, agentID, []uint{deduction.SourceID})
		if issue != "" {
			return calculationResult{}, issue
		}
		if rows[0].CharCount > len([]rune(rows[0].Answer)) || rows[0].CharCount > 12000 {
			return calculationResult{}, "Baca ketentuan pengurang secara lengkap melalui read_knowledge sebelum menghitung."
		}
		if !hasRupiahPrice(rows[0].Answer, deduction.UnitPrice) || !s.hasCustomerPriceQuantity(in.Quantity, 0, rows[0].Answer) {
			return calculationResult{}, "Nominal pengurang atau kategori jumlah tidak cocok dengan sumber resmi dan pesan pelanggan."
		}
		total := deduction.UnitPrice * in.Quantity
		remainder := result.Subtotal - total
		result.DeductionSubtotal, result.Remainder = &total, &remainder
		result.Notice += " Pengurang adalah rencana hitung sesuai ketentuan sumber, bukan bukti DP sudah dibayar."
		s.calculationSourceIDs = append(s.calculationSourceIDs, deduction.SourceID)
	}
	raw, _ := json.Marshal(result)
	s.recordBusinessFact(fmt.Sprintf("calculation:%d:%d", in.ProductID, in.SourceID), string(raw))
	if in.SourceID != 0 {
		s.calculationSourceIDs = append(s.calculationSourceIDs, in.SourceID)
	}
	return result, ""
}
func makeCalculationTool(agentID uint, s *agentTurnState) (tool.BaseTool, error) {
	return utils.InferTool("calculate_total", "Hitung harga resmi × jumlah unit/peserta pelanggan. Field subtract opsional menghitung total pengurang resmi per unit (misalnya DP) dan sisa. Baca kedua sumber terlebih dahulu. Bukan bukti pesanan/pembayaran dan tidak menyetujui diskon.", func(ctx context.Context, in calculationInput) (*agentToolResult, error) {
		if err := s.reserveTool("calculate_total"); err != nil {
			return exhaustedAgentToolResult(), nil
		}
		ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
		defer cancel()
		ctx, span := startAISpan(ctx, "calculate_total", "tool")
		defer span.End()
		result, issue := s.calculateTotal(ctx, agentID, in)
		if issue != "" {
			return &agentToolResult{Notice: issue}, nil
		}
		return &agentToolResult{Data: result}, nil
	})
}

// Refreshing any business source invalidates derived totals as well.
func (s *agentTurnState) clearCalculations() {
	for key := range s.businessBlocks {
		if strings.HasPrefix(key, "calculation:") {
			delete(s.businessBlocks, key)
		}
	}
	s.calculationSourceIDs = nil
	if s.businessBlocks != nil {
		s.recordBusinessFact("calculation_note", "")
	}
}
