"""
UzorZen Utility Functions
Yordamchi funksiyalar va vositalar
"""

import os
import json
from datetime import datetime
from jinja2 import Environment, FileSystemLoader, Template


def setup_matplotlib_for_plotting():
    """
    Setup matplotlib and seaborn for plotting with proper configuration.
    Call this function before creating any plots to ensure proper rendering.
    """
    import warnings
    import matplotlib.pyplot as plt
    import seaborn as sns

    # Ensure warnings are printed
    warnings.filterwarnings('default')  # Show all warnings

    # Configure matplotlib for non-interactive mode
    plt.switch_backend("Agg")

    # Set chart style
    plt.style.use("seaborn-v0_8")
    sns.set_palette("husl")

    # Configure platform-appropriate fonts for cross-platform compatibility
    # Must be set after style.use, otherwise will be overridden by style configuration
    plt.rcParams["font.sans-serif"] = ["Noto Sans CJK SC", "WenQuanYi Zen Hei", "PingFang SC", "Arial Unicode MS", "Hiragino Sans GB"]
    plt.rcParams["axes.unicode_minus"] = False


def create_component_library():
    """
    Komponentlar kutubxonasini yaratish
    """
    components = {
        "navbar": {
            "description": "Responsive navigation bar",
            "example": 'page.navbar("Brand Name", links=["Home", "About"])'
        },
        "hero": {
            "description": "Hero section with call-to-action",
            "example": 'page.hero("Welcome", "Subtitle text")'
        },
        "card": {
            "description": "Content card with image and text",
            "example": 'page.add_card("Title", "Description", image_url)'
        },
        "modal": {
            "description": "Popup modal dialog",
            "example": 'page.modal("modal1", "Title", "Content")'
        },
        "gallery": {
            "description": "Image gallery with lightbox",
            "example": 'page.gallery(["img1.jpg", "img2.jpg"])'
        },
        "footer": {
            "description": "Site footer with links",
            "example": 'page.footer("Footer text", links_list)'
        }
    }
    
    return components


def generate_markdown_docs():
    """
    Markdown formatida hujjat yaratish
    """
    return "UzorZen Documentation"


def create_project_structure(project_name):
    """
    Loyiha strukturasini yaratish
    """
    structure = {
        f"{project_name}/": [
            "index.html",
            "styles/",
            "scripts/",
            "images/",
            "README.md"
        ],
        f"{project_name}/styles/": [
            "main.css",
            "components.css"
        ],
        f"{project_name}/scripts/": [
            "main.js"
        ],
        f"{project_name}/images/": []
    }
    
    return structure


def export_project_config(page, config_file="uzorzen_config.json"):
    """
    Loyiha konfiguratsiyasini eksport qilish
    """
    config = {
        "title": page.title,
        "theme": page.theme,
        "created_at": datetime.now().isoformat(),
        "components": len(page.content),
        "custom_css": len(page.styles),
        "custom_js": len(page.scripts)
    }
    
    with open(config_file, 'w', encoding='utf-8') as f:
        json.dump(config, f, indent=2, ensure_ascii=False)
    
    return config


def validate_image_url(url):
    """
    Rasm URLini tekshirish
    """
    image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
    return any(url.lower().endswith(ext) for ext in image_extensions)


def create_responsive_breakpoints():
    """
    Responsive breakpoints ma'lumotlari
    """
    breakpoints = {
        "xs": "0px",
        "sm": "576px", 
        "md": "768px",
        "lg": "992px",
        "xl": "1200px",
        "xxl": "1400px"
    }
    
    return breakpoints


def get_bootstrap_colors():
    """
    Bootstrap ranglar ro'yxati
    """
    colors = {
        "primary": "#0d6efd",
        "secondary": "#6c757d", 
        "success": "#198754",
        "danger": "#dc3545",
        "warning": "#ffc107",
        "info": "#0dcaf0",
        "light": "#f8f9fa",
        "dark": "#212529"
    }
    
    return colors


def create_sample_images():
    """
    Namuna rasmlar ro'yxati
    """
    images = [
        "https://images.unsplash.com/photo-1461749280684-dccba630e2f6?ixlib=rb-4.0.3&auto=format&fit=crop&w=2070&q=80",
        "https://images.unsplash.com/photo-1551650975-87deedd944c3?ixlib=rb-4.0.3&auto=format&fit=crop&w=1974&q=80",
        "https://images.unsplash.com/photo-1543286386-2e659306cd6c?ixlib=rb-4.0.3&auto=format&fit=crop&w=2070&q=80",
        "https://images.unsplash.com/photo-1454165804606-c3d57bc86b40?ixlib=rb-4.0.3&auto=format&fit=crop&w=2070&q=80",
        "https://images.unsplash.com/photo-1557804506-669a67965ba0?ixlib=rb-4.0.3&auto=format&fit=crop&w=1974&q=80"
    ]
    
    return images


def optimize_for_seo(page):
    """
    SEO uchun sahifani optimallashtirish
    """
    seo_friendly_title = page.title.lower().replace(" ", "-")
    
    # Meta ma'lumotlarni qo'shish
    seo_js = f"""
    // SEO optimizatsiyasi
    document.title = '{page.title}';
    
    // Meta description
    const metaDesc = document.createElement('meta');
    metaDesc.name = 'description';
    metaDesc.content = '{page.title} - Zamonaviy web sahifa UzorZen orqali yaratilgan';
    document.head.appendChild(metaDesc);
    
    // Open Graph meta
    const ogTitle = document.createElement('meta');
    ogTitle.property = 'og:title';
    ogTitle.content = '{page.title}';
    document.head.appendChild(ogTitle);
    
    const ogDesc = document.createElement('meta');
    ogDesc.property = 'og:description';
    ogDesc.content = 'Zamonaviy web sahifa UzorZen orqali yaratilgan';
    document.head.appendChild(ogDesc);
    """
    
    page.add_js(seo_js)
    
    return seo_friendly_title


def create_pwa_manifest():
    """
    Progressive Web App manifest yaratish
    """
    manifest = {
        "name": "UzorZen Web Site",
        "short_name": "UzorZen",
        "description": "Zamonaviy web sahifa",
        "start_url": "/",
        "display": "standalone",
        "background_color": "#ffffff",
        "theme_color": "#0d6efd",
        "icons": [
            {
                "src": "/images/icon-192.png",
                "sizes": "192x192",
                "type": "image/png"
            },
            {
                "src": "/images/icon-512.png", 
                "sizes": "512x512",
                "type": "image/png"
            }
        ]
    }
    
    return manifest