import re

from intranet.search.core.query import parse_query as pq
from intranet.search.abovemeta.decider.rules.base import Rule
from intranet.search.abovemeta.decider.triggers import (
    All,
    Always,
    Any,
    ContentTrigger,
    Optional,
    RegexTrigger,
    SearchTrigger,
)

definitions = [
    Rule(
        search='meta',
        name='meta',
        collection='meta_with_at',
        scope=['search'],
        zone='search_results',
        trigger=Any(
            SearchTrigger('meta', 'meta_with_at'),
            Always(),
            feature_enabled='has_full_search_access',
        ),
    ),
    Rule(
        search='wiki',
        name='meta_wiki_only',
        collection='wiki',
        scope=['search'],
        zone='search_results',
        trigger=Any(
            SearchTrigger('wiki'),
            Always(),
            feature_disabled='has_full_search_access',
        ),
    ),
    Rule(
        search='invite',
        name='invite',
        scope=['search'],
        zone='wizard',
        trigger=All(
            # Правило-гвоздь, чтобы увеличить вес колдунщику в случае запроса с ключевыми словами
            Optional(ContentTrigger('переговорка', 0.5)),
            SearchTrigger('invite'),
            feature_enabled='has_full_search_access',
        ),
    ),
    Rule(
        search='equipment',
        name='equipment',
        scope=['search'],
        zone='wizard',
        trigger=All(
            SearchTrigger('equipment'),
            # Правило-гвоздь, чтобы увеличить вес колдунщику в случае запроса с ключевыми словами
            Optional(
                ContentTrigger(
                    ['принтер', 'сканер', 'printer', 'scanner'],
                    weight=0.5,
                    replace_query=False
                ),
            ),
            feature_enabled='has_full_search_access',
        )
    ),
    Rule(
        search='people',
        name='people-wizard',
        scope=['search'],
        zone='wizard',
        trigger=SearchTrigger('people', feature_enabled='has_peoplesearch_access'),
        groupings=[{'field': '', 'per_page': 2}],
    ),
    Rule(
        search='plan',
        collection='services',
        name='services',
        scope=['search'],
        zone='wizard',
        trigger=SearchTrigger('plan', 'services', feature_enabled='has_abcsearch_access'),
        groupings=[{'field': '', 'per_page': 1}],
    ),
    Rule(
        search='mldescription',
        name='mldescription',
        scope=['search'],
        zone='wizard',
        trigger=All(
            # Правило-гвоздь, чтобы увеличить вес колдунщику в случае запроса с ключевыми словами
            Optional(ContentTrigger(['рассылка', 'ml'], weight=0.5)),
            SearchTrigger('mldescription'),
            feature_enabled='has_full_search_access',
        ),
    ),
    Rule(
        search='st',
        name='st-serp',
        scope=['search'],
        zone='wizard',
        trigger=SearchTrigger('st', feature_enabled='has_stsearch_access'),
        groupings=[{'field': '', 'per_page': 3}],
    ),
    Rule(
        search='meta',
        collection='doc',
        name='metadoc',
        scope=['docsearch'],
        zone='search_results',
        trigger=Always(),
        groupings=[{'field': 'base_url', 'per_page': 10, 'per_group': 1}],
    ),
    Rule(
        search='people',
        name='people_person',  # person - fingerprint
        scope=['peoplesearch'],
        zone='search_results',
        trigger=RegexTrigger(
            pattern=r'(?P<start>.* )?(?P<fp>(?:[0-9a-f][0-9a-f]:){15}[0-9a-f][0-9a-f])(?P<end> .*)?',
            replace=lambda m: 's_fingerprint:"%s"' % m.group('fp'),
            replace_with_query=True,
            weight=1.0,
        ),
    ),
    Rule(
        search='people',
        name='people_person',
        scope=['peoplesearch'],
        zone='search_results',
        trigger=SearchTrigger(
            search='people',
            query=pq(
                'z_people_name:#{qtree}# i_is_robot:0 | '
                'z_people_login:#{qtree}# i_is_robot:0'
            ),
            split_text=True,
            weight=0.9,
        ),
    ),
    Rule(
        search='people',
        name='people_person',
        scope=['peoplesearch'],
        zone='search_results',
        trigger=Always(),
    ),
    Rule(
        search='wiki',
        name='wiki',
        scope=['wikisearch'],
        zone='search_results',
        trigger=Always(),
    ),
    Rule(
        search='st',
        name='st',
        scope=['stsearch'],
        zone='search_results',
        trigger=Always(),
        groupings=[{'field': '', 'per_page': 20}],
    ),
    Rule(
        search='at',
        name='at',
        scope=['atsearch'],
        zone='search_results',
        trigger=Always(feature_disabled='at_use_posts'),
    ),
    Rule(
        search='at',
        collection='posts',
        name='at_posts',
        scope=['atsearch'],
        zone='search_results',
        trigger=Always(feature_enabled='at_use_posts'),
    ),
    Rule(
        search='at',
        collection='clubs',
        name='clubs',
        scope=['atsearch'],
        zone='wizard',
        trigger=Always(),
    ),
    Rule(
        search='stat',
        name='stat',
        scope=['statsearch'],
        zone='search_results',
        trigger=Always(),
    ),
    Rule(
        search='meta',
        collection='lego',
        name='lego',
        scope=['legosearch'],
        zone='search_results',
        trigger=Always(),
        groupings=[{'field': 'lego_grp', 'per_page': 10, 'per_group': 100}],
    ),
    Rule(
        search='mldescription',
        name='mldescription',
        scope=['docsearch', 'peoplesearch', 'wikisearch'],
        zone='wizard',
        trigger=Any(
            All(
                Optional(
                    RegexTrigger(
                        pattern=r'[\w+.-]+(@)(?:[^\w]|$)',
                        replace=lambda m: re.sub('@', '', m.group(0)),
                        # FIXME: здесь были неименованные аргументы, и фактически было
                        #  replace_with_query=0.4 – похоже на опечатку
                        weight=0.4,
                    ),
                ),
                SearchTrigger(
                    search='mldescription',
                    weight=0.8,
                    query=pq(
                        's_name:#{qtree}# | '
                        'z_mldescription_name:#{qtree}# | '
                        's_email:#{qtree}# | '
                        's_exchange:#{qtree}#'
                    ),
                    replace_query=True,
                ),
            ),
            ContentTrigger(['рассылка', 'адрес', 'maillist', 'ml'], 0.8),
        ),
    ),
    Rule(
        search='femida',
        name='femida',
        scope=['femidasearch'],
        zone='search_results',
        trigger=Always(),
        groupings=[{'field': '', 'per_page': 30}],
    ),
    Rule(
        search='femida',
        collection='candidates',
        name='candidates',
        scope=['candidatesearch'],
        zone='search_results',
        trigger=Always(),
        groupings=[{'field': '', 'per_page': 20}],
    ),
    Rule(
        search='goals',
        name='goals',
        scope=['goalsearch'],
        zone='search_results',
        trigger=Always(),
    ),
    Rule(
        search='plan',
        collection='services',
        name='abc',
        scope=['abcsearch'],
        zone='search_results',
        trigger=Always(),
        formula='abc',
    ),
    Rule(
        search='meta',
        collection='conductor',
        name='conductor',
        scope=['csearch'],
        zone='search_results',
        trigger=Always(),
    ),
    Rule(
        search='ml',
        name='ml',
        scope=['mlsearch'],
        zone='search_results',
        trigger=Always(),
    ),
    Rule(
        search='st',
        collection='yasen',
        name='yasen',
        scope=['yasensearch'],
        zone='search_results',
        trigger=Always(),
    ),
    Rule(
        search='moebius',
        name='moebius',
        scope=['moebiussearch'],
        zone='search_results',
        trigger=Always(),
    ),
    Rule(
        search='moebius',
        name='moebius-serp',
        scope=['search'],
        zone='wizard',
        trigger=All(SearchTrigger('moebius', feature_enabled='has_moebiussearch_access'), Always(weight=0.03)),
        groupings=[{'field': '', 'per_page': 3}],
    ),
    Rule(
        search='meta',
        collection='map',
        name='metamap',
        scope=['mapsearch'],
        zone='search_results',
        trigger=Always(),
    ),
    Rule(
        search='help',
        name='help',
        scope=['search'],
        zone='wizard',
        trigger=All(
            Optional(ContentTrigger('услуга', 0.5)),
            SearchTrigger('help'),
            feature_enabled='has_full_search_access',
        ),
    ),
]
