package repository

import (
	"context"
	"time"
)

// TaskProvider defines the interface for task management systems (GitHub, Gitea, etc.)
type TaskProvider interface {
	// Task lifecycle management
	ListAvailableTasks() ([]*Task, error)
	ClaimTask(issueNumber int64, agentID string) (*Task, error)
	CompleteTask(issueNumber int64, agentID string, results map[string]interface{}) error
	
	// Task metadata
	GetTask(issueNumber int64) (*Task, error)
	
	// Configuration
	GetConfig() *Config
}

// Task represents a unified task interface across different providers
type Task struct {
	// Basic task information
	ID          int64     `json:"id"`
	Number      int64     `json:"number"`
	Title       string    `json:"title"`
	Description string    `json:"description"`
	State       string    `json:"state"`       // open, closed
	Provider    string    `json:"provider"`    // github, gitea
	Repository  string    `json:"repository"`  // owner/repo
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
	
	// Assignment information
	Assignee    string   `json:"assignee,omitempty"`
	Labels      []string `json:"labels"`
	
	// Bzzz-specific metadata
	TaskType          string                 `json:"task_type"`
	Priority          int                    `json:"priority"`
	Requirements      []string               `json:"requirements"`
	Deliverables      []string               `json:"deliverables"`
	Context           map[string]interface{} `json:"context"`
	RequiredRole      string                 `json:"required_role"`
	RequiredExpertise []string               `json:"required_expertise"`
	
	// Role-based assignment hints
	PreferredAgents   []string               `json:"preferred_agents,omitempty"`
	ExcludedAgents    []string               `json:"excluded_agents,omitempty"`
	CollaborationMode string                 `json:"collaboration_mode,omitempty"` // solo, pair, team
}

// Config represents unified configuration for task providers
type Config struct {
	// Provider type
	Provider string `json:"provider"` // "github" or "gitea"
	
	// Connection details
	BaseURL     string `json:"base_url"`
	AccessToken string `json:"access_token"`
	Owner       string `json:"owner"`
	Repository  string `json:"repository"`
	
	// Task management settings
	TaskLabel       string `json:"task_label"`
	InProgressLabel string `json:"in_progress_label"`
	CompletedLabel  string `json:"completed_label"`
	Assignee        string `json:"assignee"`
	
	// Branch management
	BaseBranch   string `json:"base_branch"`
	BranchPrefix string `json:"branch_prefix"`
}

// TaskFilter represents criteria for filtering tasks
type TaskFilter struct {
	// Basic filters
	State     string   `json:"state,omitempty"`     // open, closed, all
	Labels    []string `json:"labels,omitempty"`    // Must have these labels
	Assignee  string   `json:"assignee,omitempty"`  // Assigned to specific user
	
	// Role-based filters
	RequiredRole      string   `json:"required_role,omitempty"`
	RequiredExpertise []string `json:"required_expertise,omitempty"`
	
	// Priority filters
	MinPriority int `json:"min_priority,omitempty"`
	MaxPriority int `json:"max_priority,omitempty"`
	
	// Task type filters
	TaskTypes []string `json:"task_types,omitempty"`
	
	// Pagination
	Page    int `json:"page,omitempty"`
	PerPage int `json:"per_page,omitempty"`
}

// AssignmentRequest represents a task assignment request
type AssignmentRequest struct {
	TaskNumber int64  `json:"task_number"`
	AgentID    string `json:"agent_id"`
	AgentRole  string `json:"agent_role,omitempty"`
	Reason     string `json:"reason,omitempty"`
}

// CompletionResult represents task completion information
type CompletionResult struct {
	TaskNumber    int64                  `json:"task_number"`
	AgentID       string                 `json:"agent_id"`
	Status        string                 `json:"status"`        // success, failed, partial
	Results       map[string]interface{} `json:"results"`
	ErrorMessage  string                 `json:"error_message,omitempty"`
	PullRequestURL string                `json:"pull_request_url,omitempty"`
	BranchName    string                 `json:"branch_name,omitempty"`
	CommitSHA     string                 `json:"commit_sha,omitempty"`
}

// ProviderFactory creates task providers based on configuration
type ProviderFactory interface {
	CreateProvider(ctx context.Context, config *Config) (TaskProvider, error)
	SupportedProviders() []string
}

// TaskMatcher defines interface for role-based task assignment
type TaskMatcher interface {
	// Match tasks to agent roles and expertise
	MatchTasksToRole(tasks []*Task, role string, expertise []string) ([]*Task, error)
	
	// Score task suitability for an agent
	ScoreTaskForAgent(task *Task, agentRole string, expertise []string) float64
	
	// Get recommended agents for a task
	GetRecommendedAgents(task *Task, availableAgents []AgentInfo) ([]AgentInfo, error)
}

// AgentInfo represents information about an available agent
type AgentInfo struct {
	ID            string   `json:"id"`
	Role          string   `json:"role"`
	Expertise     []string `json:"expertise"`
	CurrentTasks  int      `json:"current_tasks"`
	MaxTasks      int      `json:"max_tasks"`
	Status        string   `json:"status"`
	LastSeen      time.Time `json:"last_seen"`
	Performance   float64  `json:"performance"`   // Performance score 0-1
	Availability  float64  `json:"availability"`  // Availability score 0-1
}

// TaskEvent represents events that can trigger actions
type TaskEvent struct {
	Type        string    `json:"type"`        // created, updated, assigned, completed, commented
	TaskNumber  int64     `json:"task_number"`
	Repository  string    `json:"repository"`
	Timestamp   time.Time `json:"timestamp"`
	Actor       string    `json:"actor"`       // User who triggered the event
	Data        map[string]interface{} `json:"data"`
}

// WebhookHandler defines interface for handling repository webhooks
type WebhookHandler interface {
	HandleWebhook(payload []byte, eventType string) (*TaskEvent, error)
	SupportedEvents() []string
}