package quality

import (
	"time"
)

// Dimension represents a quality dimension category
type Dimension string

const (
	DimensionFileHealth        Dimension = "File health"
	DimensionCodeQuality       Dimension = "Code quality"
	DimensionDuplication       Dimension = "Duplication"
	DimensionTestHealth        Dimension = "Test health"
	DimensionSecurity          Dimension = "Security"
	DimensionNamingQuality     Dimension = "Naming Quality"
	DimensionErrorConsistency  Dimension = "Error Consistency"
	DimensionAbstractionFit    Dimension = "Abstraction Fit"
	DimensionLogicClarity      Dimension = "Logic Clarity"
	DimensionAIGeneratedDebt   Dimension = "AI Generated Debt"
	DimensionTypeSafety        Dimension = "Type Safety"
	DimensionContractCoherence Dimension = "Contract Coherence"
	DimensionElegance          Dimension = "Elegance"
	DimensionContracts         Dimension = "Contracts"
)

// DetectorMetrics represents metrics for a specific detector
type DetectorMetrics struct {
	Potential        int     `json:"potential"`
	PassRate         float64 `json:"pass_rate"`
	Issues           int     `json:"issues"`
	WeightedFailures float64 `json:"weighted_failures"`
}

// DimensionScore represents the score for a quality dimension
type DimensionScore struct {
	Score     float64                     `json:"score"`
	Strict    float64                     `json:"strict"`
	Checks    int                         `json:"checks"`
	Issues    int                         `json:"issues"`
	Tier      int                         `json:"tier"`
	Detectors map[string]*DetectorMetrics `json:"detectors"`
}

// ScanStats represents scanning statistics
type ScanStats struct {
	Total         int                   `json:"total"`
	Open          int                   `json:"open"`
	Fixed         int                   `json:"fixed"`
	AutoResolved  int                   `json:"auto_resolved"`
	Wontfix       int                   `json:"wontfix"`
	FalsePositive int                   `json:"false_positive"`
	ByTier        map[string]*TierStats `json:"by_tier"`
}

// TierStats represents statistics for a severity tier
type TierStats struct {
	Open          int `json:"open"`
	Fixed         int `json:"fixed"`
	AutoResolved  int `json:"auto_resolved"`
	Wontfix       int `json:"wontfix"`
	FalsePositive int `json:"false_positive"`
}

// DetectorTransparency represents transparency information for detectors
type DetectorTransparency struct {
	Rows   []DetectorRow  `json:"rows"`
	Totals DetectorTotals `json:"totals"`
}

// DetectorRow represents a single detector's transparency data
type DetectorRow struct {
	Detector      string `json:"detector"`
	Visible       int    `json:"visible"`
	Suppressed    int    `json:"suppressed"`
	Excluded      int    `json:"excluded"`
	TotalDetected int    `json:"total_detected"`
}

// DetectorTotals represents totals for detector transparency
type DetectorTotals struct {
	Visible    int `json:"visible"`
	Suppressed int `json:"suppressed"`
	Excluded   int `json:"excluded"`
	Detectors  int `json:"detectors"`
}

// Potentials represents potential scores by language
type Potentials struct {
	Languages map[string]*LanguagePotentials `json:"languages"`
}

// LanguagePotentials represents potential scores for a language
type LanguagePotentials struct {
	Logs             int `json:"logs"`
	Unused           int `json:"unused"`
	Exports          int `json:"exports"`
	Deprecated       int `json:"deprecated"`
	Structural       int `json:"structural"`
	FlatDirs         int `json:"flat_dirs"`
	Props            int `json:"props"`
	SingleUse        int `json:"single_use"`
	Coupling         int `json:"coupling"`
	Cycles           int `json:"cycles"`
	Orphaned         int `json:"orphaned"`
	Patterns         int `json:"patterns"`
	Naming           int `json:"naming"`
	Facade           int `json:"facade"`
	TestCoverage     int `json:"test_coverage"`
	Smells           int `json:"smells"`
	React            int `json:"react"`
	Security         int `json:"security"`
	SubjectiveReview int `json:"subjective_review"`
	Dupes            int `json:"dupes"`
}

// CodebaseMetrics represents metrics about the codebase
type CodebaseMetrics struct {
	Languages map[string]*LanguageMetrics `json:"languages"`
}

// LanguageMetrics represents metrics for a specific language
type LanguageMetrics struct {
	TotalFiles       int `json:"total_files"`
	TotalLOC         int `json:"total_loc"`
	TotalDirectories int `json:"total_directories"`
}

// StrictTarget represents the target scoring information
type StrictTarget struct {
	Target  float64 `json:"target"`
	Current float64 `json:"current"`
	Gap     float64 `json:"gap"`
	State   string  `json:"state"`
	Warning *string `json:"warning"`
}

// Narrative represents the analysis narrative
type Narrative struct {
	Phase            string               `json:"phase"`
	Headline         string               `json:"headline"`
	Dimensions       *NarrativeDimensions `json:"dimensions"`
	Actions          []string             `json:"actions"`
	Strategy         *NarrativeStrategy   `json:"strategy"`
	Tools            *NarrativeTools      `json:"tools"`
	Debt             *NarrativeDebt       `json:"debt"`
	Milestone        string               `json:"milestone"`
	PrimaryAction    *string              `json:"primary_action"`
	WhyNow           string               `json:"why_now"`
	VerificationStep *string              `json:"verification_step"`
	RiskFlags        []string             `json:"risk_flags"`
	StrictTarget     *StrictTarget        `json:"strict_target"`
	Reminders        []string             `json:"reminders"`
	ReminderHistory  *ReminderHistory     `json:"reminder_history"`
}

// NarrativeDimensions represents dimension analysis in narrative
type NarrativeDimensions struct {
	LowestDimensions     []*DimensionInfo `json:"lowest_dimensions"`
	BiggestGapDimensions []*DimensionInfo `json:"biggest_gap_dimensions"`
	StagnantDimensions   []*DimensionInfo `json:"stagnant_dimensions"`
}

// DimensionInfo represents information about a dimension
type DimensionInfo struct {
	Name              string   `json:"name"`
	Strict            float64  `json:"strict"`
	Issues            int      `json:"issues"`
	Impact            float64  `json:"impact"`
	Subjective        bool     `json:"subjective"`
	ImpactDescription string   `json:"impact_description"`
	StuckScans        *int     `json:"stuck_scans,omitempty"`
	Lenient           *float64 `json:"lenient,omitempty"`
	Gap               *float64 `json:"gap,omitempty"`
	WontfixCount      *int     `json:"wontfix_count,omitempty"`
}

// NarrativeStrategy represents strategy information
type NarrativeStrategy struct {
	FixerLeverage  *FixerLeverage         `json:"fixer_leverage"`
	Lanes          map[string]interface{} `json:"lanes"`
	CanParallelize bool                   `json:"can_parallelize"`
	Hint           string                 `json:"hint"`
}

// FixerLeverage represents fixer leverage information
type FixerLeverage struct {
	AutoFixableCount int     `json:"auto_fixable_count"`
	TotalCount       int     `json:"total_count"`
	Coverage         float64 `json:"coverage"`
	ImpactRatio      float64 `json:"impact_ratio"`
	Recommendation   string  `json:"recommendation"`
}

// NarrativeTools represents available tools
type NarrativeTools struct {
	Fixers []interface{} `json:"fixers"`
	Move   *MoveTool     `json:"move"`
	Plan   *PlanTool     `json:"plan"`
	Badge  *BadgeTool    `json:"badge"`
}

// MoveTool represents the move tool
type MoveTool struct {
	Available bool    `json:"available"`
	Relevant  bool    `json:"relevant"`
	Reason    *string `json:"reason"`
	Usage     string  `json:"usage"`
}

// PlanTool represents the plan tool
type PlanTool struct {
	Command     string `json:"command"`
	Description string `json:"description"`
}

// BadgeTool represents the badge tool
type BadgeTool struct {
	Generated      bool    `json:"generated"`
	InReadme       bool    `json:"in_readme"`
	Path           string  `json:"path"`
	Recommendation *string `json:"recommendation"`
}

// NarrativeDebt represents debt analysis
type NarrativeDebt struct {
	OverallGap     float64 `json:"overall_gap"`
	WontfixCount   int     `json:"wontfix_count"`
	WorstDimension string  `json:"worst_dimension"`
	WorstGap       float64 `json:"worst_gap"`
	Trend          string  `json:"trend"`
}

// ReminderHistory represents reminder history
type ReminderHistory struct {
	ReportScores                   int `json:"report_scores"`
	AutoFixersAvailable            int `json:"auto_fixers_available"`
	DryRunFirst                    int `json:"dry_run_first"`
	ZoneClassification             int `json:"zone_classification"`
	FPCalibrationExportsProduction int `json:"fp_calibration_exports_production"`
	FeedbackNudge                  int `json:"feedback_nudge"`
	WontfixGrowing                 int `json:"wontfix_growing"`
	StagnantNudge                  int `json:"stagnant_nudge"`
	ReviewNotRun                   int `json:"review_not_run"`
	BadgeRecommendation            int `json:"badge_recommendation"`
}

// QualityConfig represents enhanced quality configuration
type QualityConfig struct {
	ReviewMaxAgeDays            int                    `json:"review_max_age_days"`
	HolisticMaxAgeDays          int                    `json:"holistic_max_age_days"`
	GenerateScorecard           bool                   `json:"generate_scorecard"`
	BadgePath                   string                 `json:"badge_path"`
	Exclude                     []string               `json:"exclude"`
	Ignore                      []string               `json:"ignore"`
	IgnoreMetadata              map[string]interface{} `json:"ignore_metadata"`
	ZoneOverrides               map[string]interface{} `json:"zone_overrides"`
	ReviewDimensions            []string               `json:"review_dimensions"`
	ReviewAllowCustomDimensions bool                   `json:"review_allow_custom_dimensions"`
	ReviewCustomDimensions      []string               `json:"review_custom_dimensions"`
	LargeFilesThreshold         int                    `json:"large_files_threshold"`
	PropsThreshold              int                    `json:"props_threshold"`
	FindingNoiseBudget          int                    `json:"finding_noise_budget"`
	FindingNoiseGlobalBudget    int                    `json:"finding_noise_global_budget"`
	TargetStrictScore           int                    `json:"target_strict_score"`
	Languages                   map[string]interface{} `json:"languages"`
}

// EnhancedStatus represents the comprehensive status response
type EnhancedStatus struct {
	Command              string                        `json:"command"`
	OverallScore         float64                       `json:"overall_score"`
	ObjectiveScore       float64                       `json:"objective_score"`
	StrictScore          float64                       `json:"strict_score"`
	StrictAllDetected    float64                       `json:"strict_all_detected"`
	DimensionScores      map[Dimension]*DimensionScore `json:"dimension_scores"`
	Stats                *ScanStats                    `json:"stats"`
	ScanCount            int                           `json:"scan_count"`
	LastScan             time.Time                     `json:"last_scan"`
	ByTier               map[string]*TierStats         `json:"by_tier"`
	Ignores              []string                      `json:"ignores"`
	Suppression          *SuppressionInfo              `json:"suppression"`
	DetectorTransparency *DetectorTransparency         `json:"detector_transparency"`
	Potentials           *Potentials                   `json:"potentials"`
	CodebaseMetrics      *CodebaseMetrics              `json:"codebase_metrics"`
	StrictTarget         *StrictTarget                 `json:"strict_target"`
	Narrative            *Narrative                    `json:"narrative"`
	Config               *QualityConfig                `json:"config"`
}

// SuppressionInfo represents suppression information
type SuppressionInfo struct {
	LastIgnored         int     `json:"last_ignored"`
	LastRawFindings     int     `json:"last_raw_findings"`
	LastSuppressedPct   float64 `json:"last_suppressed_pct"`
	LastIgnorePatterns  int     `json:"last_ignore_patterns"`
	RecentScans         int     `json:"recent_scans"`
	RecentIgnored       int     `json:"recent_ignored"`
	RecentRawFindings   int     `json:"recent_raw_findings"`
	RecentSuppressedPct float64 `json:"recent_suppressed_pct"`
}
