"""
Subscription Model - Service subscriptions for clients
"""
from sqlalchemy import Column, String, Integer, ForeignKey, Numeric, Date, JSON, Boolean
from sqlalchemy.orm import relationship
from enum import Enum
from datetime import date

from app.models.base import BaseModel


class ServiceType(str, Enum):
    CHATBOT = "chatbot"
    VOICE_AGENT = "voice_agent"
    DOCUMENT_INTELLIGENCE = "document_intelligence"
    ANALYTICS = "analytics"
    VISION = "vision"


class SubscriptionStatus(str, Enum):
    ACTIVE = "active"
    PAUSED = "paused"
    CANCELLED = "cancelled"
    EXPIRED = "expired"
    TRIAL = "trial"
    PENDING_PAYMENT = "pending_payment"


class PlanTier(str, Enum):
    FREE = "free"
    STARTER = "starter"
    PROFESSIONAL = "professional"
    ENTERPRISE = "enterprise"
    CUSTOM = "custom"


class Subscription(BaseModel):
    """
    Subscription model - tracks which services each client has subscribed to
    """
    __tablename__ = "subscriptions"

    # Client
    client_id = Column(Integer, ForeignKey("clients.id", ondelete="CASCADE"), nullable=False, index=True)

    # Service & Plan
    service_type = Column(String(50), nullable=False, index=True)
    plan_tier = Column(String(50), default=PlanTier.STARTER, nullable=False)
    plan_name = Column(String(100), nullable=False)

    # Pricing
    price_monthly = Column(Numeric(10, 2), nullable=False)
    price_yearly = Column(Numeric(10, 2), nullable=True)
    billing_cycle = Column(String(20), default="monthly")  # monthly, yearly, custom
    currency = Column(String(3), default="INR")

    # Dates
    start_date = Column(Date, nullable=False, default=date.today)
    end_date = Column(Date, nullable=True)
    trial_end_date = Column(Date, nullable=True)
    next_billing_date = Column(Date, nullable=True)
    cancelled_at = Column(Date, nullable=True)

    # Status
    status = Column(String(50), default=SubscriptionStatus.TRIAL, nullable=False)
    auto_renew = Column(Boolean, default=True)

    # Usage Limits
    usage_limits = Column(JSON, default={})
    # Example: {
    #   "messages_per_month": 10000,
    #   "documents_per_month": 500,
    #   "api_calls_per_month": 50000,
    #   "storage_gb": 10
    # }

    # Current Usage (reset monthly)
    current_usage = Column(JSON, default={})

    # Features included
    features = Column(JSON, default=[])
    # Example: ["custom_branding", "priority_support", "api_access", "webhooks"]

    # Payment
    stripe_subscription_id = Column(String(100), nullable=True)
    razorpay_subscription_id = Column(String(100), nullable=True)

    # Metadata
    extra_data = Column("metadata", JSON, default={})  # Renamed to avoid SQLAlchemy reserved word

    # Relationships
    client = relationship("Client", back_populates="subscriptions")

    def __repr__(self):
        return f"<Subscription {self.service_type} - {self.plan_name}>"

    @property
    def is_active(self) -> bool:
        return self.status in [SubscriptionStatus.ACTIVE, SubscriptionStatus.TRIAL]

    @property
    def is_trial(self) -> bool:
        return self.status == SubscriptionStatus.TRIAL

    @property
    def days_remaining(self) -> int:
        if not self.end_date:
            return -1  # Unlimited
        return (self.end_date - date.today()).days

    def get_usage_percentage(self, metric: str) -> float:
        """Get usage percentage for a specific metric"""
        limit = self.usage_limits.get(metric, 0)
        used = self.current_usage.get(metric, 0)
        if limit == 0:
            return 0
        return round((used / limit) * 100, 2)
