package ai_test

import (
	"os"
	"path/filepath"
	"testing"

	"inboxer/src/internal/ai"
	"inboxer/src/internal/imap"
)

func TestParseClassification(t *testing.T) {
	tests := []struct {
		name       string
		input      string
		wantFolder string
		wantScore  int
		wantErr    bool
	}{
		{
			name:       "important",
			input:      `{"folder": "Important", "score": 85, "context": "Work-related email"}`,
			wantFolder: "Important",
			wantScore:  85,
		},
		{
			name:       "ecommerce",
			input:      `{"folder": "eCommerce", "score": 90, "context": "Shopping confirmation"}`,
			wantFolder: "eCommerce",
			wantScore:  90,
		},
		{
			name:       "spam",
			input:      `{"folder": "Spam", "score": 95, "context": "Unsolicited"}`,
			wantFolder: "Spam",
			wantScore:  95,
		},
		{
			name:       "other",
			input:      `{"folder": "Other", "score": 50, "context": "Newsletter"}`,
			wantFolder: "Other",
			wantScore:  50,
		},
		{
			name:       "notifications",
			input:      `{"folder": "Notifications", "score": 90, "context": "Password reset"}`,
			wantFolder: "Notifications",
			wantScore:  90,
		},
		{
			name:       "finance",
			input:      `{"folder": "Finance", "score": 85, "context": "Bank statement"}`,
			wantFolder: "Finance",
			wantScore:  85,
		},
		{
			name:       "social",
			input:      `{"folder": "Social", "score": 70, "context": "Twitter notification"}`,
			wantFolder: "Social",
			wantScore:  70,
		},
		{
			name:    "invalid folder",
			input:   `{"folder": "Unknown", "score": 50, "context": "Test"}`,
			wantErr: true,
		},
		{
			name:    "score too low",
			input:   `{"folder": "Other", "score": 0, "context": "Test"}`,
			wantErr: true,
		},
		{
			name:    "score too high",
			input:   `{"folder": "Other", "score": 101, "context": "Test"}`,
			wantErr: true,
		},
		{
			name:    "not json",
			input:   `not json at all`,
			wantErr: true,
		},
		{
			name:    "empty string",
			input:   ``,
			wantErr: true,
		},
		{
			name:       "extra whitespace in json",
			input:      `  {"folder": "Important", "score": 75, "context": "Test"}  `,
			wantFolder: "Important",
			wantScore:  75,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result, err := ai.ParseClassification(tt.input)
			if tt.wantErr {
				if err == nil {
					t.Fatal("expected error, got nil")
				}
				return
			}
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			if result.Folder != tt.wantFolder {
				t.Errorf("expected folder %q, got %q", tt.wantFolder, result.Folder)
			}
			if result.Score != tt.wantScore {
				t.Errorf("expected score %d, got %d", tt.wantScore, result.Score)
			}
		})
	}
}

func TestNewClassifierInvalidPrompt(t *testing.T) {
	api := ai.NewDeepSeekAPI("test-key", "deepseek-chat", 1000, 0.1)
	_, err := ai.NewClassifier(api, "/nonexistent/prompt.txt")
	if err == nil {
		t.Fatal("expected error with nonexistent prompt file")
	}
}

func TestNewClassifierValidPrompt(t *testing.T) {
	dir := t.TempDir()
	promptFile := filepath.Join(dir, "prompt.txt")
	err := os.WriteFile(promptFile, []byte("Classify this email: {sender} {subject} {body}"), 0644)
	if err != nil {
		t.Fatalf("failed to write prompt file: %v", err)
	}

	api := ai.NewDeepSeekAPI("test-key", "deepseek-chat", 1000, 0.1)
	classifier, err := ai.NewClassifier(api, promptFile)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if classifier == nil {
		t.Fatal("expected non-nil classifier")
	}
}

func TestNewDeepSeekAPI(t *testing.T) {
	api := ai.NewDeepSeekAPI("sk-test-key", "deepseek-chat", 500, 0.5)
	if api == nil {
		t.Fatal("NewDeepSeekAPI returned nil")
	}
}

func TestNewClassifierFromBin(t *testing.T) {
	// Test that bin/prompt.txt can be loaded (exists in project)
	api := ai.NewDeepSeekAPI("test-key", "deepseek-chat", 1000, 0.1)

	classifier, err := ai.NewClassifier(api, "prompt.txt")
	if err != nil {
		// If CWD isn't project root, this may fail; that's acceptable
		t.Logf("relative path failed (maybe not in project root): %v", err)
		_ = classifier
	}
}

func TestClassifierNoAPIKey(t *testing.T) {
	// Test that classifying with a fake API key returns an error (doesn't panic)
	dir := t.TempDir()
	promptFile := filepath.Join(dir, "prompt.txt")
	err := os.WriteFile(promptFile, []byte("Classify: {sender} {subject} {body}"), 0644)
	if err != nil {
		t.Fatalf("write prompt: %v", err)
	}

	api := ai.NewDeepSeekAPI("sk-fake-key", "deepseek-chat", 1000, 0.1)
	classifier, err := ai.NewClassifier(api, promptFile)
	if err != nil {
		t.Fatalf("NewClassifier failed: %v", err)
	}

	_, _, err = classifier.Classify(imap.EmailSummary{
		From:    "test@example.com",
		Subject: "Test",
		Body:    "Body text",
	})
	// Should fail because API key is fake (connection refused or auth error)
	if err == nil {
		t.Log("no error with fake API key (network may be mocked)")
	}
}

func TestNewDeepSeekAPIDefaults(t *testing.T) {
	api := ai.NewDeepSeekAPI("test-key", "deepseek-chat", 1000, 0.1)
	if api == nil {
		t.Fatal("expected non-nil API client")
	}
}
