"""
Enterprise AI Knowledge Base
Comprehensive documentation of all application features, models, and capabilities
"""

from typing import Dict, List, Any
import logging

logger = logging.getLogger(__name__)


class AIKnowledgeBase:
    """Enterprise Knowledge Base for AI Assistant - Documents entire application"""
    
    APPLICATION_OVERVIEW = """
    This is a comprehensive Hotel Booking and Management System (HBMS) - an enterprise-grade
    solution for managing hotel operations, reservations, payments, guest services, and business analytics.
    
    The system supports multiple user roles: Admin, Staff, Accountant, and Customer, each with
    different access levels and permissions.
    """
    
    # Core Models and Features
    FEATURES = {
        "booking_management": {
            "description": "Complete booking lifecycle management including creation, confirmation, check-in, check-out, and cancellation",
            "models": ["Booking", "BookingStatus"],
            "key_fields": ["booking_number", "user_id", "room_id", "check_in_date", "check_out_date", 
                          "num_guests", "total_price", "status", "special_requests"],
            "statuses": ["pending", "confirmed", "checked_in", "checked_out", "cancelled"],
            "relationships": ["User", "Room", "Payment", "Invoice", "ServiceUsage", "CheckInCheckOut"]
        },
        
        "room_management": {
            "description": "Room inventory, availability, status tracking, and maintenance",
            "models": ["Room", "RoomType", "RoomStatus"],
            "key_fields": ["room_number", "floor", "status", "price", "capacity", "amenities", "room_size", "view"],
            "statuses": ["available", "occupied", "maintenance", "cleaning"],
            "relationships": ["RoomType", "Booking", "Review", "RoomMaintenance", "HousekeepingTask"]
        },
        
        "payment_processing": {
            "description": "Payment handling for bookings with multiple payment methods and status tracking",
            "models": ["Payment", "PaymentMethod", "PaymentStatus", "PaymentType"],
            "key_fields": ["amount", "payment_method", "payment_type", "payment_status", "transaction_id", "payment_date"],
            "payment_methods": ["cash", "credit_card", "debit_card", "bank_transfer", "e_wallet", "stripe", "paypal", "borica"],
            "statuses": ["pending", "completed", "failed", "refunded"],
            "payment_types": ["full", "deposit", "remaining"],
            "relationships": ["Booking"]
        },
        
        "invoice_management": {
            "description": "Invoice generation, tracking, and payment reconciliation",
            "models": ["Invoice", "InvoiceItem", "InvoiceStatus"],
            "key_fields": ["invoice_number", "total_amount", "subtotal", "tax_amount", "discount_amount", 
                          "balance_due", "status", "due_date", "paid_date"],
            "statuses": ["draft", "sent", "paid", "overdue", "cancelled"],
            "relationships": ["Booking", "User", "InvoiceItem"]
        },
        
        "user_management": {
            "description": "User accounts, roles, authentication, and guest profiles",
            "models": ["User", "Role", "RefreshToken", "PasswordResetToken"],
            "key_fields": ["email", "full_name", "phone", "role_id", "is_active", "currency"],
            "roles": ["admin", "staff", "customer", "accountant"],
            "guest_fields": ["is_vip", "lifetime_value", "satisfaction_score", "total_visits", "last_visit_date"],
            "relationships": ["Role", "Booking", "Payment", "Invoice", "Review", "Favorite"]
        },
        
        "loyalty_program": {
            "description": "Customer loyalty program with tiers, points, rewards, and referrals",
            "models": ["LoyaltyTier", "UserLoyalty", "LoyaltyPointTransaction", "LoyaltyReward", 
                      "RewardRedemption", "Referral"],
            "key_fields": ["tier_level", "points_balance", "lifetime_points", "referral_code"],
            "relationships": ["User", "Booking"]
        },
        
        "service_management": {
            "description": "Additional hotel services like spa, restaurant, room service",
            "models": ["Service", "ServiceUsage", "ServiceBooking", "ServiceBookingItem", "ServicePayment"],
            "key_fields": ["service_name", "price", "category", "description"],
            "relationships": ["Booking"]
        },
        
        "promotion_system": {
            "description": "Discount codes, promotional campaigns, and special offers",
            "models": ["Promotion"],
            "key_fields": ["code", "discount_type", "discount_value", "start_date", "end_date", "is_active"],
            "relationships": ["Booking"]
        },
        
        "reviews_and_ratings": {
            "description": "Guest reviews and ratings for rooms and services",
            "models": ["Review"],
            "key_fields": ["rating", "comment", "is_verified"],
            "relationships": ["User", "Room"]
        },
        
        "chat_system": {
            "description": "Real-time chat support between guests and staff",
            "models": ["Chat", "ChatMessage", "ChatStatus"],
            "key_fields": ["visitor_name", "visitor_email", "status", "message", "sender_type", "is_read"],
            "statuses": ["open", "closed"],
            "relationships": ["User"]
        },
        
        "check_in_check_out": {
            "description": "Check-in and check-out process management",
            "models": ["CheckInCheckOut"],
            "key_fields": ["checked_in_at", "checked_out_at", "checked_in_by", "checked_out_by", "notes"],
            "relationships": ["Booking", "User"]
        },
        
        "maintenance_tracking": {
            "description": "Room maintenance scheduling and tracking",
            "models": ["RoomMaintenance", "RoomInspection"],
            "key_fields": ["scheduled_start", "scheduled_end", "status", "description", "priority"],
            "relationships": ["Room"]
        },
        
        "housekeeping": {
            "description": "Housekeeping task management and scheduling",
            "models": ["HousekeepingTask"],
            "key_fields": ["task_type", "status", "scheduled_time", "completed_at"],
            "relationships": ["Room"]
        },
        
        "guest_management": {
            "description": "Comprehensive guest profile management and CRM features",
            "models": ["GuestNote", "GuestPreference", "GuestTag", "GuestSegment", "GuestCommunication"],
            "key_fields": ["notes", "preferences", "tags", "communication_history"],
            "relationships": ["User"]
        },
        
        "group_bookings": {
            "description": "Group booking management for multiple rooms",
            "models": ["GroupBooking"],
            "key_fields": ["group_name", "contact_person", "total_rooms", "group_discount"],
            "relationships": ["Booking"]
        },
        
        "rate_plans": {
            "description": "Dynamic pricing and rate plan management",
            "models": ["RatePlan"],
            "key_fields": ["name", "base_price", "season_multiplier", "valid_from", "valid_to"],
            "relationships": ["Booking"]
        },
        
        "packages": {
            "description": "Pre-configured booking packages (room + services)",
            "models": ["Package"],
            "key_fields": ["name", "price", "includes", "valid_period"],
            "relationships": ["RoomType", "Service"]
        },
        
        "blog_and_content": {
            "description": "Content management for hotel blog and marketing",
            "models": ["BlogPost", "Banner", "PageContent"],
            "key_fields": ["title", "content", "is_published", "published_at"],
            "relationships": []
        },
        
        "analytics_and_reporting": {
            "description": "Business intelligence, analytics, and financial reporting",
            "features": ["Revenue reports", "Occupancy analytics", "Guest analytics", "Payment reports", 
                       "Invoice reports", "Booking trends", "Customer lifetime value"],
            "models": ["AuditLog"]
        },
        
        "system_settings": {
            "description": "System-wide configuration and settings",
            "models": ["SystemSettings"],
            "key_fields": ["key", "value", "category"],
            "categories": ["general", "payment", "email", "company_info"]
        },
        
        "security_and_compliance": {
            "description": "Security, audit logging, and GDPR compliance",
            "models": ["SecurityEvent", "AuditLog", "GDPRCompliance"],
            "features": ["Action audit trails", "Security event logging", "GDPR data requests", 
                        "Cookie consent management"]
        },
        
        "notifications": {
            "description": "System notifications and alerts",
            "models": ["Notification"],
            "key_fields": ["type", "message", "is_read", "priority"],
            "relationships": ["User"]
        },
        
        "workflows": {
            "description": "Automated workflow management for business processes",
            "models": ["Workflow"],
            "key_fields": ["name", "trigger", "actions", "conditions"],
            "relationships": []
        },
        
        "email_campaigns": {
            "description": "Marketing email campaigns and automation",
            "models": ["EmailCampaign"],
            "key_fields": ["subject", "content", "recipient_segment", "scheduled_time"],
            "relationships": ["GuestSegment"]
        }
    }
    
    ROLE_CAPABILITIES = {
        "admin": {
            "description": "Full system access with all administrative privileges",
            "can_access": [
                "All bookings (all customers)",
                "All rooms and room management",
                "All payments and financial data",
                "All invoices",
                "All users and user management",
                "System settings and configuration",
                "Analytics and reports",
                "Audit logs and security events",
                "Content management (blog, banners, pages)",
                "Promotion management",
                "Loyalty program administration",
                "Service management",
                "Maintenance and housekeeping",
                "Check-in/check-out operations",
                "Chat management",
                "Email campaigns",
                "Workflow management",
                "Group bookings",
                "Rate plans and packages"
            ],
            "cannot_access": [],
            "restrictions": "None - full access"
        },
        
        "accountant": {
            "description": "Financial data access for accounting and reporting",
            "can_access": [
                "All payments and payment history",
                "All invoices and invoice management",
                "Financial reports and analytics",
                "Revenue summaries",
                "Payment reconciliation",
                "Invoice generation and editing",
                "Booking financial details (for invoicing)",
                "Customer payment history",
                "Refund processing",
                "Financial dashboard statistics"
            ],
            "cannot_access": [
                "User personal information (except payment-related)",
                "System settings",
                "Content management",
                "Room operational details (unless related to billing)",
                "Security and audit logs (financial audit access only)"
            ],
            "restrictions": "Financial and payment data only"
        },
        
        "staff": {
            "description": "Operational staff with access to daily hotel operations",
            "can_access": [
                "All bookings and booking management",
                "Room status and availability",
                "Check-in and check-out operations",
                "Guest information (for operations)",
                "Room maintenance and housekeeping tasks",
                "Service bookings and service usage",
                "Chat system for customer support",
                "Basic booking reports",
                "Occupancy status",
                "Group bookings",
                "Guest preferences and notes (operational)"
            ],
            "cannot_access": [
                "Financial reports and analytics",
                "System settings",
                "User management (except guest profile updates)",
                "Content management",
                "Email campaigns",
                "Workflow management",
                "Full payment details (can view payment status only)",
                "Invoice editing (view only)"
            ],
            "restrictions": "Operational data only, no financial or system administration"
        },
        
        "customer": {
            "description": "Hotel guests with access to their own booking and account information",
            "can_access": [
                "Own bookings (view, cancel)",
                "Own booking details",
                "Own invoices (view only)",
                "Own payment history",
                "Own profile information",
                "Room browsing and availability (public)",
                "Service browsing",
                "Booking creation",
                "Review submission",
                "Favorite rooms",
                "Loyalty points and rewards",
                "Referral code usage",
                "Chat with support"
            ],
            "cannot_access": [
                "Other customers' bookings or information",
                "All bookings overview",
                "Financial reports",
                "System settings",
                "Room management",
                "Staff operations",
                "Admin features",
                "Other users' data"
            ],
            "restrictions": "Only own data and customer-facing features"
        }
    }
    
    COMMON_QUERIES = {
        "booking": [
            "booking status", "check-in date", "check-out date", "booking number",
            "cancel booking", "modify booking", "upcoming bookings", "past bookings"
        ],
        "room": [
            "available rooms", "room types", "room amenities", "room prices",
            "room availability", "occupied rooms", "room status"
        ],
        "payment": [
            "payment status", "payment history", "payment methods", "refund",
            "outstanding balance", "payment due", "transaction"
        ],
        "invoice": [
            "invoice status", "invoice number", "invoice amount", "due date",
            "paid invoice", "outstanding invoice", "invoice download"
        ],
        "loyalty": [
            "loyalty points", "loyalty tier", "rewards", "referral code",
            "points balance", "points history"
        ],
        "general": [
            "hotel information", "contact", "policies", "services", "amenities",
            "location", "FAQ", "help"
        ]
    }
    
    @classmethod
    def get_application_knowledge(cls) -> Dict[str, Any]:
        """Get comprehensive application knowledge for AI context"""
        return {
            "overview": cls.APPLICATION_OVERVIEW,
            "features": cls.FEATURES,
            "role_capabilities": cls.ROLE_CAPABILITIES,
            "common_queries": cls.COMMON_QUERIES
        }
    
    @classmethod
    def get_role_info(cls, role_name: str) -> Dict[str, Any]:
        """Get information about a specific role"""
        return cls.ROLE_CAPABILITIES.get(role_name.lower(), {})
    
    @classmethod
    def get_feature_info(cls, feature_name: str) -> Dict[str, Any]:
        """Get information about a specific feature"""
        return cls.FEATURES.get(feature_name.lower(), {})
    
    @classmethod
    def can_role_access_feature(cls, role_name: str, feature: str) -> bool:
        """Check if a role can access a specific feature"""
        role_info = cls.ROLE_CAPABILITIES.get(role_name.lower(), {})
        can_access = role_info.get("can_access", [])
        
        # Admin can access everything
        if role_name.lower() == "admin":
            return True
        
        # Check if feature is in can_access list
        feature_keywords = feature.lower().split("_")
        for accessible in can_access:
            accessible_lower = accessible.lower()
            if any(keyword in accessible_lower for keyword in feature_keywords):
                return True
        
        return False

