"""
Genesis Talking Website Widget - Tenant Manager
Multi-tenant business configuration and API key management
"""

import secrets
import hashlib
from typing import Optional, Dict, Any
from datetime import datetime
from database import db


class TenantManager:
    """Manager for multi-tenant business accounts."""

    @staticmethod
    def generate_business_id() -> str:
        """Generate unique business ID."""
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        random = secrets.token_hex(4)
        return f"bus_{timestamp}_{random}"

    @staticmethod
    def generate_api_key() -> str:
        """Generate secure API key for widget authentication."""
        # Format: gw_live_<random_64_chars>
        random_part = secrets.token_urlsafe(48)
        return f"gw_live_{random_part}"

    def create_business(
        self,
        name: str,
        website_url: Optional[str] = None,
        greeting_message: Optional[str] = None,
        agent_name: Optional[str] = None,
        primary_color: Optional[str] = None,
        knowledge_base: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """
        Create a new business tenant.

        Args:
            name: Business name
            website_url: Website URL
            greeting_message: Custom greeting
            agent_name: AI agent name
            primary_color: Brand color
            knowledge_base: Services, FAQs, etc.

        Returns:
            Business record with API key
        """
        business_id = self.generate_business_id()
        api_key = self.generate_api_key()

        import json as json_module

        config = {
            "knowledge_base": knowledge_base or {}
        }

        with db.get_cursor() as cursor:
            # Insert business
            cursor.execute("""
                INSERT INTO widget_businesses (id, name, api_key, website_url, config)
                VALUES (%s, %s, %s, %s, %s)
                RETURNING *
            """, (business_id, name, api_key, website_url, json_module.dumps(config)))

            business = dict(cursor.fetchone())

            # Insert widget config
            cursor.execute("""
                INSERT INTO widget_configs
                (business_id, agent_name, greeting_message, primary_color)
                VALUES (%s, %s, %s, %s)
                RETURNING *
            """, (
                business_id,
                agent_name or "Sarah",
                greeting_message or "Hi! Thanks for reaching out. How can I help you today?",
                primary_color or "#6366F1"
            ))

            widget_config = dict(cursor.fetchone())

        return {
            **business,
            "widget_config": widget_config
        }

    def get_business_by_id(self, business_id: str) -> Optional[Dict[str, Any]]:
        """Get business by ID."""
        with db.get_cursor() as cursor:
            cursor.execute("""
                SELECT b.*, w.agent_name, w.greeting_message, w.primary_color,
                       w.position, w.avatar_url
                FROM widget_businesses b
                LEFT JOIN widget_configs w ON b.id = w.business_id
                WHERE b.id = %s
            """, (business_id,))

            result = cursor.fetchone()
            return dict(result) if result else None

    def get_business_by_api_key(self, api_key: str) -> Optional[Dict[str, Any]]:
        """Get business by API key (for widget authentication)."""
        with db.get_cursor() as cursor:
            cursor.execute("""
                SELECT b.*, w.agent_name, w.greeting_message, w.primary_color,
                       w.position, w.avatar_url
                FROM widget_businesses b
                LEFT JOIN widget_configs w ON b.id = w.business_id
                WHERE b.api_key = %s
            """, (api_key,))

            result = cursor.fetchone()
            return dict(result) if result else None

    def update_widget_config(
        self,
        business_id: str,
        **kwargs
    ) -> bool:
        """
        Update widget configuration.

        Accepts: agent_name, greeting_message, primary_color, position, avatar_url
        """
        allowed_fields = [
            "agent_name", "greeting_message", "primary_color",
            "position", "avatar_url"
        ]

        updates = {k: v for k, v in kwargs.items() if k in allowed_fields and v is not None}

        if not updates:
            return False

        set_clause = ", ".join([f"{k} = %s" for k in updates.keys()])
        values = list(updates.values()) + [business_id]

        with db.get_cursor() as cursor:
            cursor.execute(f"""
                UPDATE widget_configs
                SET {set_clause}
                WHERE business_id = %s
            """, values)

            return cursor.rowcount > 0

    def verify_api_key(self, api_key: str) -> bool:
        """Verify if API key is valid."""
        business = self.get_business_by_api_key(api_key)
        return business is not None

    def list_businesses(self, limit: int = 100, offset: int = 0) -> list:
        """List all businesses (admin only)."""
        with db.get_cursor() as cursor:
            cursor.execute("""
                SELECT b.id, b.name, b.website_url, b.created_at,
                       COUNT(DISTINCT c.id) as total_conversations,
                       COUNT(DISTINCT l.id) as total_leads
                FROM widget_businesses b
                LEFT JOIN widget_conversations c ON b.id = c.business_id
                LEFT JOIN widget_leads l ON b.id = l.business_id
                GROUP BY b.id, b.name, b.website_url, b.created_at
                ORDER BY b.created_at DESC
                LIMIT %s OFFSET %s
            """, (limit, offset))

            return [dict(row) for row in cursor.fetchall()]


# Global tenant manager instance
tenant_manager = TenantManager()


if __name__ == "__main__":
    print("Genesis Widget API - Tenant Manager Test")
    print("=" * 60)

    # Test business creation
    print("Creating test business...")
    try:
        business = tenant_manager.create_business(
            name="Test Plumbing Co",
            website_url="https://testplumbing.com.au",
            agent_name="Sarah",
            greeting_message="Thanks for calling Test Plumbing!",
            primary_color="#6366F1"
        )
        print(f"✅ Business created: {business['id']}")
        print(f"   API Key: {business['api_key']}")
        print(f"   Agent: {business['widget_config']['agent_name']}")

        # Test retrieval
        retrieved = tenant_manager.get_business_by_id(business['id'])
        if retrieved:
            print(f"✅ Business retrieved successfully")
        else:
            print(f"❌ Failed to retrieve business")

        # Test API key verification
        if tenant_manager.verify_api_key(business['api_key']):
            print(f"✅ API key verified")
        else:
            print(f"❌ API key verification failed")

    except Exception as e:
        print(f"❌ Error: {e}")

    print("\n🏢 Tenant manager ready")
