from pydantic import BaseModel, Field
from typing import Optional
from enum import Enum


class BusinessModelKey(str, Enum):
    AFFILIATE = "affiliate"
    DIGITAL = "digital"
    SAAS = "saas"
    ECOMMERCE_DROPSHIP = "ecommerce_dropship"
    ECOMMERCE_INVENTORY = "ecommerce_inventory"
    SERVICES = "services"


class Mood(str, Enum):
    PROFESSIONAL = "professional"
    CREATIVE = "creative"
    MINIMAL = "minimal"
    BOLD = "bold"
    WARM = "warm"


class DomainIntrinsic(BaseModel):
    domain_name: str
    name_part: str
    tld: str
    length: int
    tld_multiplier: float
    length_score: float
    has_hyphens: bool
    has_numbers: bool
    raw_score: float
    domain_only_value: int


class TrafficEstimate(BaseModel):
    audience_segments: int
    affiliate_count: int
    market_heat: float
    monthly_visitors_low: int
    monthly_visitors_high: int
    monthly_visitors_mid: int


class MonthlyRevenue(BaseModel):
    gross_low: int
    gross_high: int
    fulfillment_cost_low: int
    fulfillment_cost_high: int
    overhead_low: int
    overhead_high: int
    net_profit_low: int
    net_profit_high: int
    profit_margin_pct: int


class RevenueModel(BaseModel):
    model_key: str
    label: str
    is_primary_fit: bool
    description: str
    fulfillment_cost_pct: int
    startup_cost: dict
    time_to_first_dollar_days: int
    scalability_score: float
    risk_score: float
    monthly_revenue: MonthlyRevenue
    annual_net: dict
    developed_value: dict
    valuation_multiple: str


class NicheValuation(BaseModel):
    niche_name: str
    monetization_model: str
    requires_inventory: bool
    ai_valuation_band: dict
    traffic_estimate: TrafficEstimate
    revenue_by_model: list[RevenueModel]
    best_model: Optional[dict] = None


class ValuationResult(BaseModel):
    domain: str
    domain_intrinsic: DomainIntrinsic
    domain_only_value: int
    best_developed_value: int
    best_monthly_net: int
    niches_evaluated: int
    niche_valuations: list[NicheValuation]
    fulfillment_guide: dict
    business_models: dict


class NicheInfo(BaseModel):
    name: str
    description: str
    score: float = 5.0
    monetization_model: str = "affiliate"
    target_audience: str = ""
    time_to_revenue: str = "medium"
    valuation_band: str = "1000-5000"
    affiliate_programs: list[str] = Field(default_factory=list)
    requires_inventory: bool = False
    synopsis: str = ""


class AnalysisResult(BaseModel):
    domain: str
    keywords: list[str]
    interpretations: list[str] = Field(default_factory=list)
    domain_summary: str = ""
    niches: list[NicheInfo]


class BrandOption(BaseModel):
    name: str
    tagline: str = ""


class BrandResult(BaseModel):
    options: list[BrandOption]
    recommended: int = 0
    color_primary: str = "#4F46E5"
    color_secondary: str = "#7C3AED"
    color_accent: str = "#06B6D4"
    industry_context: str = ""


class ThemeColors(BaseModel):
    primary: str
    primary_light: str
    primary_dark: str
    primary_rgb: str
    primary_text: str
    secondary: str
    secondary_light: str
    secondary_rgb: str
    accent: str
    accent_rgb: str


class ThemeConfig(BaseModel):
    mood: str
    profile: dict
    colors: ThemeColors
    card_style: str
    section_header_style: str
    border_radius: str
    shadow_intensity: str
    font_weight_heading: str
    letter_spacing: str
    background_pattern: str
    section_backgrounds: dict
    divider_pairs: dict
    dividers: dict
    icons: dict
    animated_bg_keyframes: str
    animated_bg_layers: str


class ValidationEntry(BaseModel):
    field: str
    message: str


class ValidationReport(BaseModel):
    context: str
    valid: bool
    score: int
    error_count: int
    warning_count: int
    repair_count: int
    errors: list[ValidationEntry] = Field(default_factory=list)
    warnings: list[ValidationEntry] = Field(default_factory=list)
    repairs: list[ValidationEntry] = Field(default_factory=list)


class LLMRequest(BaseModel):
    prompt: str
    system_prompt: Optional[str] = None
    max_tokens: int = 8192
    response_format: str = "json"


class LLMResponse(BaseModel):
    content: str
    model: str = ""
    usage: Optional[dict] = None


class ContextBlock(BaseModel):
    source: str
    priority: int = 0
    content: str


class FieldDefinition(BaseModel):
    key: str
    label: str
    type: str
    description: str = ""
    min_length: int = 0
    max_length: int = 0
    min_items: int = 0
    max_items: int = 0
    card_fields: list[dict] = Field(default_factory=list)
    table_fields: Optional[dict] = None


class SectionDefinition(BaseModel):
    key: str
    label: str
    description: str
    enabled: bool = True
    required: bool = False
    category: str = "core"
    fields: list[FieldDefinition] = Field(default_factory=list)
    visual_options: dict = Field(default_factory=dict)
    ai_instructions: str = ""
    order: int = 0


class BlueprintConfig(BaseModel):
    depth: str
    depth_label: str
    content_multiplier: float
    sections: list[SectionDefinition]
    global_settings: dict = Field(default_factory=dict)
    visual_settings: dict = Field(default_factory=dict)


class BlueprintValidation(BaseModel):
    valid: bool
    errors: list[str] = Field(default_factory=list)


class ValuationInput(BaseModel):
    """Input schema for the valuation MCP tool."""
    domain: str = Field(description="Domain name to valuate (e.g. 'techsolutions.com')")
    analysis: dict = Field(default_factory=dict, description="Analysis result containing niches array with name, monetization_model, valuation_band, etc.")


class ValidatorInput(BaseModel):
    """Input schema for the validator MCP tool."""
    data: dict = Field(default_factory=dict, description="Data to validate (site copy, brand, or analysis dict)")
    auto_repair: bool = Field(default=True, description="Auto-repair invalid fields with safe defaults")
    target: str = Field(default="site_copy", description="Validation target: 'site_copy', 'brand', or 'analysis'")


class ThemeInput(BaseModel):
    """Input schema for the theme MCP tool."""
    mood: str = Field(default="professional", description="Mood profile: professional, creative, minimal, bold, warm")
    primary: str = Field(default="#4F46E5", description="Primary brand color as hex")
    secondary: str = Field(default="#7C3AED", description="Secondary brand color as hex")
    accent: str = Field(default="#06B6D4", description="Accent brand color as hex")
    niche: str = Field(default="", description="Business niche for contextual theming")


class BlueprintInput(BaseModel):
    """Input schema for the blueprint MCP tool."""
    depth: str = Field(default="comprehensive", description="Depth preset: minimal (5 sections), standard (9), comprehensive (14), legendary (17)")


class OrchestratorInput(BaseModel):
    """Input schema for the orchestrator MCP tool."""
    domain: str = Field(default="example.com", description="Domain name for the business package")
    analysis: dict = Field(default_factory=dict, description="Domain analysis with niches, keywords, brand identity")
    depth: str = Field(default="comprehensive", description="Blueprint depth preset")
    mood: str = Field(default="professional", description="Theme mood profile")
    primary: str = Field(default="#4F46E5", description="Primary brand color")
    secondary: str = Field(default="#7C3AED", description="Secondary brand color")
    accent: str = Field(default="#06B6D4", description="Accent brand color")
    stages: list[str] = Field(default_factory=lambda: ["blueprint", "valuation", "context", "theme", "validator"], description="Pipeline stages to execute")
