import json
from types import SimpleNamespace

from django.db.utils import OperationalError, ProgrammingError
from django.templatetags.static import static

from .models import CompanyInformation, GoogleSettings, SEOSettings, VisitorCounter, WebsiteLikeCounter, WebsiteSettings


DEFAULT_COMPANY_INFO = {
    "company_name": "Aarya Holidays & Cabs",
    "tagline": "Curated holidays and dependable cab travel from one trusted team.",
    "introduction": (
        "Plan family getaways, group tours, corporate travel, airport transfers, "
        "and outstation cab journeys with a team that keeps every detail clear."
    ),
    "story": (
        "Aarya Holidays & Cabs brings holiday planning and cab coordination together "
        "so travellers can move from enquiry to journey with confidence."
    ),
    "mission": "To make every trip simple, comfortable, transparent, and memorable.",
    "vision": "To become a trusted travel partner for holidays and cab services across India.",
    "why_choose_text": (
        "Local route knowledge, responsive support, clear planning, and comfortable cab options "
        "make every booking feel personal and dependable."
    ),
    "phone_number": "+91 9035339515",
    "whatsapp_number": "+91 9035339515",
    "email": "aaryaholidayscabs@gmail.com",
    "address": "Sri Reddy Mahalasa Apartment, 1st floor, 3rd cross,VB layout, Krishna Raja puram, new Extension Bangalore - 560036",
    "working_hours": "Mon-Sun, 8:00 AM - 9:00 PM",
    "google_map_embed_url": "https://www.google.com/maps?q=Sri%20Reddy%20Mahalasa%20Apartment%2C%201st%20floor%2C%203rd%20cross%2CVB%20layout%2C%20Krishna%20Raja%20puram%2C%20new%20Extension%20Bangalore%20-%20560036&output=embed",
    "facebook_url": "#",
    "instagram_url": "#",
    "youtube_url": "#",
    "x_url": "#",
}


def company_information(request):
    data = DEFAULT_COMPANY_INFO.copy()
    visitor_total = 0
    website_like_total = 0
    website_like_version = 1
    seo_meta = {
        "title": "Aarya Holidays & Cabs",
        "description": "Premium holiday packages and reliable cab services from Aarya Holidays & Cabs.",
        "keywords": "holiday packages, cab services, travel planning",
        "canonical_url": "",
        "robots": "index,follow",
        "og_image": static("images/logo.jpeg"),
        "site_name": "Aarya Holidays & Cabs",
    }
    google_meta = {
        "ga4_measurement_id": "",
        "gtm_container_id": "",
        "search_console_verification": "",
        "meta_pixel_id": "",
    }
    structured_data = {
        "organization": {
            "@context": "https://schema.org",
            "@type": "Organization",
            "name": "Aarya Holidays & Cabs",
            "url": "",
            "logo": static("images/logo.jpeg"),
            "telephone": "",
            "email": "",
            "address": {
                "@type": "PostalAddress",
                "streetAddress": "",
            },
            "sameAs": [],
        },
        "local_business": {
            "@context": "https://schema.org",
            "@type": "TravelAgency",
            "name": "Aarya Holidays & Cabs",
            "image": static("images/logo.jpeg"),
            "url": "",
            "telephone": "",
            "email": "",
            "address": {
                "@type": "PostalAddress",
                "streetAddress": "",
            },
            "priceRange": "$$",
            "aggregateRating": {
                "@type": "AggregateRating",
                "ratingValue": "5.0",
                "reviewCount": "1",
            },
        },
    }
    try:
        company = CompanyInformation.objects.first()
        if company:
            for key in data:
                value = getattr(company, key, None)
                if value:
                    data[key] = value

        website_settings = WebsiteSettings.objects.first()
        if website_settings:
            website_mapping = {
                "company_name": website_settings.company_name,
                "phone_number": website_settings.phone_number,
                "whatsapp_number": website_settings.whatsapp_number,
                "email": website_settings.email,
                "address": website_settings.address,
                "working_hours": website_settings.business_hours,
                "facebook_url": website_settings.facebook_url,
                "instagram_url": website_settings.instagram_url,
                "youtube_url": website_settings.youtube_url,
                "x_url": website_settings.x_url,
                "footer_text": website_settings.footer_text,
            }
            for key, value in website_mapping.items():
                if value:
                    data[key] = value

            data["logo_url"] = website_settings.logo.url if website_settings.logo else static("images/logo.jpeg")
        else:
            data["logo_url"] = static("images/logo.jpeg")

        visitor_total = VisitorCounter.load().total_count
        like_counter = WebsiteLikeCounter.load()
        website_like_total = like_counter.total_likes
        website_like_version = like_counter.like_version

        seo_settings = SEOSettings.load()
        seo_meta["title"] = seo_settings.meta_title or seo_meta["title"]
        seo_meta["description"] = seo_settings.meta_description or seo_meta["description"]
        seo_meta["keywords"] = seo_settings.meta_keywords or seo_meta["keywords"]
        seo_meta["canonical_url"] = seo_settings.canonical_url or ""
        seo_meta["robots"] = f"{'index' if seo_settings.robots_index else 'noindex'},{'follow' if seo_settings.robots_follow else 'nofollow'}"
        if seo_settings.open_graph_image:
            seo_meta["og_image"] = seo_settings.open_graph_image.url

        google_settings = GoogleSettings.load()
        google_meta.update(
            {
                "ga4_measurement_id": google_settings.ga4_measurement_id,
                "gtm_container_id": google_settings.gtm_container_id,
                "search_console_verification": google_settings.search_console_verification,
                "meta_pixel_id": google_settings.meta_pixel_id,
            }
        )
    except (OperationalError, ProgrammingError):
        pass

    data.setdefault("logo_url", static("images/logo.jpeg"))
    data.setdefault("footer_text", data["introduction"])

    request_url = ""
    if request is not None:
        try:
            request_url = request.build_absolute_uri()
        except Exception:
            request_url = ""

    if not seo_meta["canonical_url"]:
        seo_meta["canonical_url"] = request_url

    canonical_base = seo_meta["canonical_url"] or request_url
    if canonical_base:
        seo_meta["absolute_url"] = canonical_base
    else:
        seo_meta["absolute_url"] = ""

    if seo_meta["og_image"].startswith("/") and request_url:
        root_url = request.build_absolute_uri("/").rstrip("/")
        seo_meta["og_image"] = f"{root_url}{seo_meta['og_image']}"

    same_as = [
        url
        for url in [
            data.get("facebook_url"),
            data.get("instagram_url"),
            data.get("youtube_url"),
            data.get("x_url"),
        ]
        if url and url != "#"
    ]

    structured_data["organization"].update(
        {
            "url": request.build_absolute_uri("/") if request_url else "",
            "logo": seo_meta["og_image"],
            "telephone": data.get("phone_number") or "",
            "email": data.get("email") or "",
            "sameAs": same_as,
        }
    )
    structured_data["organization"]["address"]["streetAddress"] = data.get("address") or ""

    structured_data["local_business"].update(
        {
            "image": seo_meta["og_image"],
            "url": request.build_absolute_uri("/") if request_url else "",
            "telephone": data.get("phone_number") or "",
            "email": data.get("email") or "",
        }
    )
    structured_data["local_business"]["address"]["streetAddress"] = data.get("address") or ""

    structured_data["breadcrumb"] = {
        "@context": "https://schema.org",
        "@type": "BreadcrumbList",
        "itemListElement": [
            {
                "@type": "ListItem",
                "position": 1,
                "name": "Home",
                "item": request.build_absolute_uri("/") if request_url else "",
            }
        ],
    }

    structured_data["website"] = {
        "@context": "https://schema.org",
        "@type": "WebSite",
        "name": seo_meta["site_name"],
        "url": request.build_absolute_uri("/") if request_url else "",
    }

    structured_data_json = {
        "organization": json.dumps(structured_data["organization"], ensure_ascii=False),
        "local_business": json.dumps(structured_data["local_business"], ensure_ascii=False),
        "website": json.dumps(structured_data["website"], ensure_ascii=False),
        "breadcrumb": json.dumps(structured_data["breadcrumb"], ensure_ascii=False),
    }

    return {
        "company_info": SimpleNamespace(**data),
        "visitor_count": visitor_total,
        "website_like_count": website_like_total,
        "website_like_version": website_like_version,
        "seo_meta": SimpleNamespace(**seo_meta),
        "google_meta": SimpleNamespace(**google_meta),
        "structured_data": structured_data_json,
    }
