# -*- coding: utf-8 -*-
from __future__ import annotations

import logging
import pathlib
import urllib.parse

from django import template
from django.contrib.messages import Message
from django.urls import reverse_lazy
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _

from hotpocket_backend.apps.ui.constants import (
    MessageLevelAlertClass,
    UIAccessTokenOriginApp,
)
from hotpocket_backend.apps.ui.dto.base import BrowseParams
from hotpocket_common.constants import (
    AccessTokenOriginApp,
    AssociationsSearchMode,
)
from hotpocket_soa.dto.accounts import AccessTokenOut
from hotpocket_soa.dto.saves import SaveOut

LOGGER = logging.getLogger(__name__)

register = template.Library()


@register.filter('render_url_domain')
def render_url_domain(value: str | None) -> str:
    if value is None:
        return '-'

    parsed_url = urllib.parse.urlsplit(value)
    return parsed_url.netloc


@register.filter('next_url')
def next_url(before: str, params: BrowseParams) -> str:
    if not before:
        return '#'

    url = urllib.parse.urlsplit(str(reverse_lazy(params.view_name)))._replace(
        query=urllib.parse.urlencode([
            ('before', before),
            ('search', params.search or ''),
            ('limit', params.limit),
        ]),
    )

    return url.geturl()


@register.filter('previous_url')
def previous_url(after: str, params: BrowseParams) -> str:
    if not after:
        return '#'

    url = urllib.parse.urlsplit(str(reverse_lazy(params.view_name)))._replace(
        query=urllib.parse.urlencode([
            ('after', after),
            ('search', params.search or ''),
            ('limit', params.limit),
        ]),
    )

    return url.geturl()


@register.filter('render_youtube_embed_url')
def render_youtube_embed_url(save: SaveOut) -> str | None:
    video_id: str | None = None

    if save.parsed_url.netloc.endswith('youtube.com') is True:
        if save.parsed_url.path.startswith('/live'):
            video_id = str(pathlib.PurePosixPath(save.parsed_url.path).name)
        else:
            video_id = save.parsed_url_query.get('v', [None])[0]
    elif save.parsed_url.netloc.endswith('youtu.be') is True:
        video_id = save.parsed_url.path

    if video_id is None:
        return None

    result = urllib.parse.urlsplit('https://www.youtube.com/')._replace(
        path=str(pathlib.PurePosixPath('/embed') / video_id.strip('/')),
    )

    return result.geturl()


@register.simple_tag(name='browse_associations_url')
def browse_associations_url(mode: str | None = None) -> str:
    mode_param: AssociationsSearchMode | None = None

    if mode == 'STARRED':
        mode_param = AssociationsSearchMode.STARRED
    elif mode == 'ARCHIVED':
        mode_param = AssociationsSearchMode.ARCHIVED

    query = []
    if mode_param is not None:
        query.append(('mode', mode_param.value))

    return str(reverse_lazy(
        'ui.associations.browse',
        query=query,
    ))


@register.filter(name='alert_class')
def alert_class(message: Message | None) -> str:
    if message is None:
        return 'alert-secondary'

    try:
        return MessageLevelAlertClass[message.level_tag].value
    except KeyError:
        LOGGER.debug(
            'Unknown message level tag: message.level_tag=`%s`',
            message.level_tag,
        )

    return 'alert-secondary'


@register.filter(name='render_access_token_app')
def render_access_token_app(access_token: AccessTokenOut) -> str:
    app: str = access_token.get_origin_app_id()
    variant = 'secondary'

    origin_app = access_token.get_origin_app()

    extension_origin_apps = (
        AccessTokenOriginApp.SAFARI_WEB_EXTENSION,
        AccessTokenOriginApp.CHROME_EXTENSION,
        AccessTokenOriginApp.FIREFOX_EXTENSION,
        AccessTokenOriginApp.HOTPOCKET_DESKTOP,
        AccessTokenOriginApp.HOTPOCKET_MOBILE,
    )
    if origin_app in extension_origin_apps:
        app = UIAccessTokenOriginApp[origin_app.value].value
        variant = 'info'

    return format_html(
        '<span class="badge text-bg-{}">{}</span>',
        variant,
        app,
    )


@register.filter(name='render_access_token_platform')
def render_access_token_platform(access_token: AccessTokenOut) -> str:
    match access_token.meta.get('platform', None):
        case 'MacIntel' | 'macOS':
            return 'macOS'

        case 'iPhone':
            return 'iOS'

        case 'iPad':
            return 'iPadOS'

        case 'Win32':
            return 'Windows'

        case 'Linux x86_64':
            return 'Linux'

        case 'Linux armv81':
            return 'Linux'

        case None:
            return _('Unknown')

        case _:
            return access_token.meta['platform']
