import hashlib
import re

from django.db import models, transaction
from django.db.models import Q
from django.utils import timezone
from django.utils.text import slugify
from rest_framework import serializers

from basic.models import Language

from . import models as articleModels


CONTENT_MODELS = {
    "educational_content": "EducationContent",
    "problem_solution_content": "ProblemSolutionContent",
    "relatable_content": "RelatableContent",
    "interactive_content": "InteractiveContent",
    "story_content": "StoryContent",
    "tip_quote": "TipQuote",
    "checklist": "Checklist",
    "app_actions": "AppActions",
    "content_safety": "ContentSafety",
}

CONTENT_CHILDREN = {
    "EducationContent": {
        "social_media": "EducationContentSocialMedia",
        "app_content": "EducationContentAppContent",
    },
    "EducationContentSocialMedia": {
        "image_text": "EducationContentSocialMediaImageText",
        "hashtags": "EducationContentSocialMediaHashtags",
    },
    "EducationContentAppContent": {
        "what_you_should_know": "EducationContentAppContentWhatYouShouldKnow",
    },
    "ProblemSolutionContent": {
        "social_media": "ProblemSolutionContentSocialMedia",
        "app_content": "ProblemSolutionContentAppContent",
    },
    "ProblemSolutionContentSocialMedia": {
        "image_text": "ProblemSolutionContentSocialMediaImageText",
        "hashtags": "ProblemSolutionContentSocialMediaHashtags",
    },
    "ProblemSolutionContentAppContent": {
        "possible_causes": "ProblemSolutionContentAppContentPossibleCauses",
        "recommended_solutions": "ProblemSolutionContentAppContentRecommendedSolutions",
    },
    "RelatableContent": {
        "social_media": "RelatableContentSocialMedia",
        "app_content": "RelatableContentAppContent",
    },
    "RelatableContentSocialMedia": {
        "hashtags": "RelatableContentSocialMediaHashtags",
    },
    "InteractiveContent": {
        "social_media": "InteractiveContentSocialMedia",
        "app_content": "InteractiveContentAppContent",
    },
    "InteractiveContentSocialMedia": {
        "options": "InteractiveContentSocialMediaOptions",
        "hashtags": "InteractiveContentSocialMediaHashtags",
    },
    "InteractiveContentAppContent": {
        "options": "InteractiveContentAppContentOptions",
    },
    "StoryContent": {
        "social_media": "StoryContentSocialMedia",
        "app_content": "StoryContentAppContent",
    },
    "StoryContentSocialMedia": {
        "hashtags": "StoryContentSocialMediaHashtags",
    },
    "Checklist": {"items": "ChecklistItems"},
    "AppActions": {
        "related_app_features": "AppActionsRelatedAppFeatures",
        "action_buttons": "AppActionsActionButtons",
        "related_content": "AppActionsRelatedContent",
    },
    "ContentSafety": {
        "warning_signs": "ContentSafetyWarningSigns",
        "additional_notes": "ContentSafetyAdditionalNotes",
    },
}


_EMOJI_CHARACTER = (
    r"[\U0001F000-\U0001FAFF"
    r"\u2139\u2194-\u2199\u21A9-\u21AA\u231A-\u231B\u2328\u23CF"
    r"\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA-\u25AB\u25B6\u25C0"
    r"\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614-\u2615\u2618\u261D"
    r"\u2620\u2622-\u2623\u2626\u262A\u262E-\u262F\u2638-\u263A"
    r"\u2640\u2642\u2648-\u2653\u265F-\u2660\u2663\u2665-\u2666\u2668"
    r"\u267B\u267E-\u267F\u2692-\u2697\u2699\u269B-\u269C\u26A0-\u26A1"
    r"\u26A7\u26AA-\u26AB\u26B0-\u26B1\u26BD-\u26BE\u26C4-\u26C5\u26C8"
    r"\u26CE-\u26CF\u26D1\u26D3-\u26D4\u26E9-\u26EA\u26F0-\u26F5"
    r"\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714"
    r"\u2716\u271D\u2721\u2728\u2733-\u2734\u2744\u2747\u274C\u274E"
    r"\u2753-\u2755\u2757\u2763-\u2764\u2795-\u2797\u27A1\u27B0\u27BF"
    r"\u2934-\u2935\u2B05-\u2B07"
    r"\u2B1B-\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]"
)
_EMOJI_PART = rf"{_EMOJI_CHARACTER}[\uFE0E\uFE0F]?[\U0001F3FB-\U0001F3FF]?"
_EMOJI_PATTERN = re.compile(
    r"[0-9#*]\uFE0F?\u20E3"
    r"|[\u00A9\u00AE\u203C\u2049\u2122]\uFE0F"
    rf"|{_EMOJI_PART}(?:\u200D{_EMOJI_PART})*[\U000E0020-\U000E007F]*"
)


def _plainText(value):
    # Keep Unicode text and formatting; remove complete emoji sequences only.
    text, removed = _EMOJI_PATTERN.subn("", value)
    return text.strip() if removed else text


def _jsonName(fieldName):
    return re.sub(r"(?<!^)(?=[A-Z])", "_", fieldName).lower()


def _invalid(path, message):
    raise serializers.ValidationError({path: message})


def _object(value, path):
    if not isinstance(value, dict):
        _invalid(path, "Must be an object.")
    return value


def _id(value, path):
    if isinstance(value, bool) or not str(value).isdigit() or int(value) < 1:
        _invalid(path, "Must be a positive integer.")
    return int(value)


def _parentField(model, parentModel):
    return next(
        field.name for field in model._meta.fields
        if isinstance(field, models.ForeignKey)
        and field.remote_field.model is parentModel
    )


def _one(query, path):
    records = list(query.order_by("id")[:2])
    if len(records) > 1:
        _invalid(path, "Multiple records match. Provide an explicit record ID.")
    return records[0] if records else None


class ArticleImporter:
    def __init__(self, articleData):
        self.articleData = articleData
        self.languages = {}

    def _language(self, locale, path):
        if not isinstance(locale, str) or not re.fullmatch(
            r"[A-Za-z]{2,3}(?:[_-][A-Za-z]{2})?", locale,
        ):
            _invalid(path, "Language keys must use a code such as en_gb or ar_sa.")
        normalized = locale.lower().replace("-", "_")
        if normalized not in self.languages:
            code, _, country = normalized.partition("_")
            query = Language.objects.filter(
                Q(languageCode__iexact=normalized)
                | Q(languageCode__iexact=normalized.replace("_", "-"))
            )
            language = _one(query, path)
            if language is None:
                query = Language.objects.filter(languageCode__iexact=code)
                if country:
                    language = _one(query.filter(countryCode__iexact=country), path)
                if language is None:
                    language = _one(query, path)
            if language is None:
                _invalid(path, f"Language {locale} is not configured in the Language table.")
            self.languages[normalized] = language
        return self.languages[normalized]

    def _translations(self, model, data, path):
        translationModel = getattr(articleModels, model.__name__ + "Language", None)
        translations = {}
        if translationModel is not None:
            for field in translationModel._meta.fields:
                if not isinstance(field, models.TextField):
                    continue
                name = _jsonName(field.name)
                if name not in data:
                    continue
                localized = data[name]
                if not isinstance(localized, dict):
                    continue
                for locale, value in localized.items():
                    if not isinstance(value, str):
                        continue
                    language = self._language(locale, f"{path}.{name}.{locale}")
                    translations.setdefault(language.pk, {})[field.name] = _plainText(value)
        return translationModel, translations

    def _saveTranslations(self, model, instance, data, path):
        translationModel, translations = self._translations(model, data, path)
        if not translations:
            return
        parentField = _parentField(translationModel, model)
        for languageId, values in translations.items():
            lookup = {parentField: instance, "languageId_id": languageId}
            translation = _one(translationModel.objects.filter(**lookup), path)
            self._save(translationModel, translation, lookup, values)

    @staticmethod
    def _save(model, instance, lookup, values):
        if instance is None:
            return model.objects.create(**lookup, **values)
        if values:
            for field, value in values.items():
                setattr(instance, field, value)
            instance.save(update_fields=tuple(values))
        return instance

    def _records(self, value, path):
        records = value if isinstance(value, list) else [value]
        seen = set()
        for index, record in enumerate(records):
            _object(record, f"{path}[{index}]")
            key = record.get("reference_key") or record.get("id")
            if key is not None:
                if isinstance(key, bool) or not isinstance(key, (str, int)):
                    _invalid(path, "Record IDs and reference keys must be strings or integers.")
                if str(key) in seen:
                    _invalid(path, f"Duplicate record ID or reference key: {key}.")
                seen.add(str(key))
        return records

    def _hashtags(self, value, path):
        if not isinstance(value, dict):
            return []
        records = {}
        for locale, hashtags in value.items():
            if not isinstance(hashtags, list):
                continue
            for index, hashtag in enumerate(hashtags):
                if not isinstance(hashtag, str):
                    continue
                self._language(locale, f"{path}.{locale}")
                record = records.setdefault(index, {"id": f"hashtag_{index + 1}", "text": {}})
                record["text"][locale] = hashtag
        return [records[index] for index in sorted(records)]

    def _children(self, model, instance, data, path):
        for name, childName in CONTENT_CHILDREN.get(model.__name__, {}).items():
            if name not in data:
                continue
            childPath = f"{path}.{name}"
            value = data[name]
            if name == "hashtags":
                records = self._hashtags(value, childPath)
            elif name == "related_app_features":
                if not isinstance(value, list):
                    continue
                records = []
                for feature in value:
                    if not isinstance(feature, str) or not feature.strip():
                        continue
                    records.append({"id": feature})
                records = self._records(records, childPath)
            else:
                records = self._records(value, childPath)
            childModel = getattr(articleModels, childName)
            for index, record in enumerate(records):
                self._record(childModel, instance, record, childPath, index)

    def _record(self, model, parent, data, path, index):
        _object(data, path)
        if model is articleModels.AppActionsRelatedContent and not isinstance(
            data.get("reference_key"), str,
        ):
            return
        parentField = _parentField(model, type(parent))
        lookup = {parentField: parent}
        values = {}
        for field in model._meta.fields:
            if field.primary_key or isinstance(field, models.ForeignKey):
                continue
            name = _jsonName(field.name)
            if field.name == "keyName":
                key = data.get("id")
                if key is None:
                    key = f"{path.rsplit('.', 1)[-1]}_{index + 1}"
                if isinstance(key, bool) or not isinstance(key, (str, int)) or not str(key).strip():
                    _invalid(path, "Record IDs must be non-empty strings or integers.")
                lookup["keyName"] = str(key)
            elif name in data:
                value = data[name]
                if isinstance(field, models.BooleanField):
                    if not isinstance(value, bool):
                        _invalid(f"{path}.{name}", "Must be a boolean.")
                elif isinstance(field, models.TextField):
                    if not isinstance(value, str):
                        continue
                    if field.name != "referenceKey":
                        value = _plainText(value)
                values[field.name] = value
        if model is articleModels.AppActionsRelatedContent:
            referenceKey = values.pop("referenceKey", None)
            if not referenceKey or not referenceKey.strip():
                _invalid(f"{path}.reference_key", "A non-empty reference key is required.")
            lookup["referenceKey"] = referenceKey
            if "id" in data:
                target = None
                if data["id"] is not None:
                    targetId = _id(data["id"], f"{path}.id")
                    target = articleModels.ContentInformation.objects.filter(pk=targetId).first()
                    if target is None:
                        _invalid(f"{path}.id", "The related article does not exist.")
                else:
                    target = _one(
                        articleModels.ContentInformation.objects.filter(keyName=referenceKey), path,
                    )
                values["relatedContentId"] = target
        query = model.objects.select_for_update().filter(**lookup)
        if "keyName" in lookup or "referenceKey" in lookup:
            instance = _one(query, path)
        elif data.get("id") is not None:
            recordId = _id(data["id"], f"{path}.id")
            instance = query.filter(pk=recordId).first()
            if instance is None:
                _invalid(f"{path}.id", "This record does not belong to its parent.")
        else:
            instance = next(iter(query.order_by("id")[index:index + 1]), None)
        instance = self._save(model, instance, lookup, values)
        self._saveTranslations(model, instance, data, path)
        self._children(model, instance, data, path)
        return instance

    def _information(self):
        information = dict(self.articleData["content_information"])
        for field in ("category", "subcategory"):
            if field in information:
                value = information[field]
                if isinstance(value, dict):
                    information[field] = value.get("title", value)
        return information

    def _article(self, information):
        model = articleModels.ContentInformation
        query = model.objects.select_for_update()
        _, translations = self._translations(model, information, "content_information")
        suppliedKey = information.get("keyName", information.get("key_name"))
        if not isinstance(suppliedKey, str):
            suppliedKey = None
        if suppliedKey is not None and not suppliedKey.strip():
            _invalid("content_information.keyName", "Must be a non-empty string.")
        topics = [
            value["topic"] for value in translations.values()
            if value.get("topic") and value["topic"].strip()
        ]
        if not topics and not suppliedKey and information.get("id") is None:
            _invalid("content_information.topic", "Provide a non-empty topic, keyName or article ID.")
        topic = topics[0] if topics else ""
        for locale, language in self.languages.items():
            translatedTopic = translations.get(language.pk, {}).get("topic")
            if locale.startswith("en") and translatedTopic and translatedTopic.strip():
                topic = translatedTopic
                break
        keyName = suppliedKey or slugify(
            topic.splitlines()[0] if topic else "", allow_unicode=True,
        ).replace("-", "_")
        if not keyName:
            keyName = "article_" + hashlib.sha256(topic.encode()).hexdigest()[:16]
        article = None
        if information.get("id") is not None:
            articleId = _id(information["id"], "content_information.id")
            article = query.filter(pk=articleId).first()
            if article is None:
                _invalid("content_information.id", "The article does not exist.")
        else:
            article = _one(query.filter(keyName=keyName), "content_information.keyName")
            if article is None and not suppliedKey:
                matchingTopics = Q(pk__in=[])
                for languageId, values in translations.items():
                    if values.get("topic"):
                        matchingTopics |= Q(topic__iexact=values["topic"], languageId=languageId)
                matchingIds = articleModels.ContentInformationLanguage.objects.filter(
                    matchingTopics,
                ).values("contentInformationId")
                article = _one(query.filter(pk__in=matchingIds), "content_information.topic")
        now = timezone.now()
        created = article is None
        if created:
            article = model.objects.create(keyName=keyName, createdDate=now, updatedDate=now)
        else:
            if suppliedKey and query.filter(keyName=suppliedKey).exclude(pk=article.pk).exists():
                _invalid("content_information.keyName", "This key belongs to another article.")
            article.keyName = suppliedKey or article.keyName or keyName
            article.updatedDate = now
            article.save(update_fields=("keyName", "updatedDate"))
        self._saveTranslations(model, article, information, "content_information")
        for name, childModel in (
            ("target_audience", articleModels.TargetAudience),
            ("content_objective", articleModels.ContentObjective),
        ):
            if name not in information:
                continue
            items = information[name]
            if not isinstance(items, list):
                continue
            for title in items:
                if not isinstance(title, str):
                    continue
                title = _plainText(title)
                if not childModel.objects.filter(contentInformationId=article, title=title).exists():
                    childModel.objects.create(contentInformationId=article, title=title)
        return article, created

    @transaction.atomic
    def save(self):
        information = self._information()
        if "languages" in information:
            if not isinstance(information["languages"], list):
                _invalid("content_information.languages", "Must be a list of language codes.")
            for locale in information["languages"]:
                self._language(locale, "content_information.languages")
        article, created = self._article(information)
        for name, modelName in CONTENT_MODELS.items():
            if name not in self.articleData:
                continue
            model = getattr(articleModels, modelName)
            for index, record in enumerate(self._records(self.articleData[name], name)):
                self._record(model, article, record, name, index)
        return article, created


def importArticle(articleData):
    return ArticleImporter(articleData).save()
