package roadmap

import (
	"time"

	"github.com/google/uuid"
)

// ============================================================================
// Constants / Enums
// ============================================================================

// ItemStatus represents the implementation status of a roadmap item
type ItemStatus string

const (
	ItemStatusPlanned    ItemStatus = "PLANNED"
	ItemStatusInProgress ItemStatus = "IN_PROGRESS"
	ItemStatusBlocked    ItemStatus = "BLOCKED"
	ItemStatusCompleted  ItemStatus = "COMPLETED"
	ItemStatusDeferred   ItemStatus = "DEFERRED"
)

// ItemPriority represents the priority of a roadmap item
type ItemPriority string

const (
	ItemPriorityCritical ItemPriority = "CRITICAL"
	ItemPriorityHigh     ItemPriority = "HIGH"
	ItemPriorityMedium   ItemPriority = "MEDIUM"
	ItemPriorityLow      ItemPriority = "LOW"
)

// ItemCategory represents the category of a roadmap item
type ItemCategory string

const (
	ItemCategoryTechnical      ItemCategory = "TECHNICAL"
	ItemCategoryOrganizational ItemCategory = "ORGANIZATIONAL"
	ItemCategoryProcessual     ItemCategory = "PROCESSUAL"
	ItemCategoryDocumentation  ItemCategory = "DOCUMENTATION"
	ItemCategoryTraining       ItemCategory = "TRAINING"
)

// ImportFormat represents supported import file formats
type ImportFormat string

const (
	ImportFormatExcel ImportFormat = "EXCEL"
	ImportFormatCSV   ImportFormat = "CSV"
	ImportFormatJSON  ImportFormat = "JSON"
)

// ============================================================================
// Main Entities
// ============================================================================

// Roadmap represents a compliance implementation roadmap
type Roadmap struct {
	ID          uuid.UUID  `json:"id"`
	TenantID    uuid.UUID  `json:"tenant_id"`
	NamespaceID *uuid.UUID `json:"namespace_id,omitempty"`

	Title       string `json:"title"`
	Description string `json:"description,omitempty"`
	Version     string `json:"version"`

	// Linked entities
	AssessmentID *uuid.UUID `json:"assessment_id,omitempty"` // Link to UCCA assessment
	PortfolioID  *uuid.UUID `json:"portfolio_id,omitempty"`  // Link to use case portfolio

	// Status tracking
	Status         string `json:"status"` // "draft", "active", "completed", "archived"
	TotalItems     int    `json:"total_items"`
	CompletedItems int    `json:"completed_items"`
	Progress       int    `json:"progress"` // Percentage 0-100

	// Dates
	StartDate  *time.Time `json:"start_date,omitempty"`
	TargetDate *time.Time `json:"target_date,omitempty"`

	// Audit
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	CreatedBy uuid.UUID `json:"created_by"`
}

// RoadmapItem represents a single item in the compliance roadmap
type RoadmapItem struct {
	ID        uuid.UUID `json:"id"`
	RoadmapID uuid.UUID `json:"roadmap_id"`

	// Core fields
	Title       string       `json:"title"`
	Description string       `json:"description,omitempty"`
	Category    ItemCategory `json:"category"`
	Priority    ItemPriority `json:"priority"`
	Status      ItemStatus   `json:"status"`

	// Compliance mapping
	ControlID     string `json:"control_id,omitempty"`     // e.g., "CTRL-AVV"
	RegulationRef string `json:"regulation_ref,omitempty"` // e.g., "DSGVO Art. 28"
	GapID         string `json:"gap_id,omitempty"`         // e.g., "GAP_AVV_MISSING"

	// Effort estimation
	EffortDays     *int `json:"effort_days,omitempty"`
	EffortHours    *int `json:"effort_hours,omitempty"`
	EstimatedCost  *int `json:"estimated_cost,omitempty"` // EUR

	// Assignment
	AssigneeID   *uuid.UUID `json:"assignee_id,omitempty"`
	AssigneeName string     `json:"assignee_name,omitempty"`
	Department   string     `json:"department,omitempty"`

	// Timeline
	PlannedStart *time.Time `json:"planned_start,omitempty"`
	PlannedEnd   *time.Time `json:"planned_end,omitempty"`
	ActualStart  *time.Time `json:"actual_start,omitempty"`
	ActualEnd    *time.Time `json:"actual_end,omitempty"`

	// Dependencies
	DependsOn  []uuid.UUID `json:"depends_on,omitempty"`  // IDs of items this depends on
	BlockedBy  []uuid.UUID `json:"blocked_by,omitempty"`  // IDs of blocking items

	// Evidence
	EvidenceRequired []string `json:"evidence_required,omitempty"`
	EvidenceProvided []string `json:"evidence_provided,omitempty"`

	// Notes
	Notes      string `json:"notes,omitempty"`
	RiskNotes  string `json:"risk_notes,omitempty"`

	// Import metadata
	SourceRow  int    `json:"source_row,omitempty"`  // Row number from import file
	SourceFile string `json:"source_file,omitempty"` // Original filename

	// Ordering
	SortOrder int `json:"sort_order"`

	// Audit
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

// ============================================================================
// Import/Export Structures
// ============================================================================

// ImportJob represents an import job
type ImportJob struct {
	ID        uuid.UUID    `json:"id"`
	TenantID  uuid.UUID    `json:"tenant_id"`
	RoadmapID *uuid.UUID   `json:"roadmap_id,omitempty"` // Target roadmap (nil = create new)

	// File info
	Filename     string       `json:"filename"`
	Format       ImportFormat `json:"format"`
	FileSize     int64        `json:"file_size"`
	ContentType  string       `json:"content_type"`

	// Status
	Status       string `json:"status"` // "pending", "parsing", "validating", "completed", "failed"
	ErrorMessage string `json:"error_message,omitempty"`

	// Parsing results
	TotalRows     int `json:"total_rows"`
	ValidRows     int `json:"valid_rows"`
	InvalidRows   int `json:"invalid_rows"`
	ImportedItems int `json:"imported_items"`

	// Parsed items (before confirmation)
	ParsedItems []ParsedItem `json:"parsed_items,omitempty"`

	// Audit
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	CompletedAt *time.Time `json:"completed_at,omitempty"`
	CreatedBy uuid.UUID  `json:"created_by"`
}

// ParsedItem represents a single parsed item from import
type ParsedItem struct {
	RowNumber    int    `json:"row_number"`
	IsValid      bool   `json:"is_valid"`
	Errors       []string `json:"errors,omitempty"`
	Warnings     []string `json:"warnings,omitempty"`

	// Extracted data
	Data         RoadmapItemInput `json:"data"`

	// Auto-mapping results
	MatchedControl    string  `json:"matched_control,omitempty"`
	MatchedRegulation string  `json:"matched_regulation,omitempty"`
	MatchedGap        string  `json:"matched_gap,omitempty"`
	MatchConfidence   float64 `json:"match_confidence,omitempty"` // 0.0 - 1.0
}

// RoadmapItemInput represents input for creating/updating a roadmap item
type RoadmapItemInput struct {
	Title         string       `json:"title"`
	Description   string       `json:"description,omitempty"`
	Category      ItemCategory `json:"category,omitempty"`
	Priority      ItemPriority `json:"priority,omitempty"`
	Status        ItemStatus   `json:"status,omitempty"`

	ControlID     string `json:"control_id,omitempty"`
	RegulationRef string `json:"regulation_ref,omitempty"`
	GapID         string `json:"gap_id,omitempty"`

	EffortDays    *int   `json:"effort_days,omitempty"`
	AssigneeName  string `json:"assignee_name,omitempty"`
	Department    string `json:"department,omitempty"`

	PlannedStart  *time.Time `json:"planned_start,omitempty"`
	PlannedEnd    *time.Time `json:"planned_end,omitempty"`

	Notes         string `json:"notes,omitempty"`
}

// ============================================================================
// API Request/Response Types
// ============================================================================

// CreateRoadmapRequest is the API request for creating a roadmap
type CreateRoadmapRequest struct {
	Title        string     `json:"title"`
	Description  string     `json:"description,omitempty"`
	AssessmentID *uuid.UUID `json:"assessment_id,omitempty"`
	PortfolioID  *uuid.UUID `json:"portfolio_id,omitempty"`
	StartDate    *time.Time `json:"start_date,omitempty"`
	TargetDate   *time.Time `json:"target_date,omitempty"`
}

// CreateRoadmapResponse is the API response for creating a roadmap
type CreateRoadmapResponse struct {
	Roadmap Roadmap `json:"roadmap"`
}

// ImportUploadResponse is returned after uploading a file for import
type ImportUploadResponse struct {
	JobID        uuid.UUID `json:"job_id"`
	Filename     string    `json:"filename"`
	Format       string    `json:"format"`
	Status       string    `json:"status"`
	Message      string    `json:"message"`
}

// ImportParseResponse is returned after parsing the uploaded file
type ImportParseResponse struct {
	JobID       uuid.UUID    `json:"job_id"`
	Status      string       `json:"status"`
	TotalRows   int          `json:"total_rows"`
	ValidRows   int          `json:"valid_rows"`
	InvalidRows int          `json:"invalid_rows"`
	Items       []ParsedItem `json:"items"`
	ColumnMap   map[string]string `json:"column_map"` // Detected column mappings
}

// ImportConfirmRequest is the request to confirm and execute import
type ImportConfirmRequest struct {
	JobID         uuid.UUID `json:"job_id"`
	RoadmapID     *uuid.UUID `json:"roadmap_id,omitempty"` // Target roadmap (nil = create new)
	RoadmapTitle  string     `json:"roadmap_title,omitempty"` // If creating new
	SelectedRows  []int      `json:"selected_rows,omitempty"` // Specific rows to import (nil = all valid)
	ApplyMappings bool       `json:"apply_mappings"` // Apply auto-detected control/regulation mappings
}

// ImportConfirmResponse is returned after confirming import
type ImportConfirmResponse struct {
	RoadmapID     uuid.UUID `json:"roadmap_id"`
	ImportedItems int       `json:"imported_items"`
	SkippedItems  int       `json:"skipped_items"`
	Message       string    `json:"message"`
}

// RoadmapFilters defines filters for listing roadmaps
type RoadmapFilters struct {
	Status       string
	AssessmentID *uuid.UUID
	PortfolioID  *uuid.UUID
	Limit        int
	Offset       int
}

// RoadmapItemFilters defines filters for listing roadmap items
type RoadmapItemFilters struct {
	Status      ItemStatus
	Priority    ItemPriority
	Category    ItemCategory
	AssigneeID  *uuid.UUID
	ControlID   string
	SearchQuery string
	Limit       int
	Offset      int
}

// RoadmapStats contains statistics for a roadmap
type RoadmapStats struct {
	TotalItems      int            `json:"total_items"`
	ByStatus        map[string]int `json:"by_status"`
	ByPriority      map[string]int `json:"by_priority"`
	ByCategory      map[string]int `json:"by_category"`
	ByDepartment    map[string]int `json:"by_department"`
	OverdueItems    int            `json:"overdue_items"`
	UpcomingItems   int            `json:"upcoming_items"` // Due in next 7 days
	TotalEffortDays int            `json:"total_effort_days"`
	Progress        int            `json:"progress"`
}
