package application

import (
	"context"
	"fmt"
	"strings"

	"github.com/mmmy/snapgo/internal/infrastructure/clipboard"
)

// OCRRecognizer describes a provider capable of extracting text from a PNG
// screenshot.
type OCRRecognizer interface {
	RecognizeText(ctx context.Context, pngBytes []byte) (string, error)
}

// CaptureOCRService wires screenshot bytes -> OCR provider -> clipboard. It
// leaves progress reporting to the caller so native and web overlays can share
// the same status HUD.
type CaptureOCRService struct {
	Recognizer OCRRecognizer
	Clipboard  clipboard.Writer
}

// Recognize asks the configured OCR provider to extract text from the PNG.
func (s *CaptureOCRService) Recognize(ctx context.Context, pngBytes []byte) (string, error) {
	if s.Recognizer == nil {
		return "", fmt.Errorf("ocr is not configured")
	}
	if len(pngBytes) == 0 {
		return "", fmt.Errorf("empty screenshot")
	}
	text, err := s.Recognizer.RecognizeText(ctx, pngBytes)
	if err != nil {
		return "", err
	}
	text = strings.TrimSpace(text)
	if text == "" {
		return "", fmt.Errorf("ocr result is empty")
	}
	return text, nil
}

// CopyText writes the extracted text to the clipboard.
func (s *CaptureOCRService) CopyText(_ context.Context, text string) error {
	text = strings.TrimSpace(text)
	if text == "" {
		return fmt.Errorf("empty ocr text")
	}
	if s.Clipboard == nil {
		return fmt.Errorf("clipboard is not configured")
	}
	if err := s.Clipboard.WriteText(text); err != nil {
		return fmt.Errorf("clipboard write failed: %w", err)
	}
	return nil
}
