File size: 5,333 Bytes
e6be672
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# Copyright (C) 2026 Mattia Zatelli
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

"""
Base plugin class for the modular intent system.

BaseIntentPlugin extends the existing BaseIntentHandler to inherit all
query-building, aggregation, and result-creation helpers while adding
plugin-specific metadata and auto-dispatch capabilities.
"""

import logging
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any
from datetime import datetime

from sqlalchemy.ext.asyncio import AsyncSession

from app.models import Project
from app.schemas.intent import SingleQueryPlan, SingleQueryResult
from app.services.intent_handlers.base_handler import BaseIntentHandler

logger = logging.getLogger(__name__)


@dataclass
class AuthorInfo:
    """Author information for the plugin."""
    name: str
    url: Optional[str] = None


@dataclass
class SubIntentMetadata:
    """Metadata for a single sub-intent declared in manifest.yaml."""
    id: str
    description: str
    examples: Dict[str, List[str]] = field(default_factory=dict)
    handler_method: str = ""


@dataclass
class IntentMetadata:
    """Metadata loaded from manifest.yaml."""
    id: str
    version: str
    name: str
    description: str
    category: str
    enabled: bool
    priority: int
    author: AuthorInfo
    sub_intents: Dict[str, SubIntentMetadata] = field(default_factory=dict)
    i18n: Dict[str, Any] = field(default_factory=dict)
    prompt_fragment: Optional[str] = None
    depends_on: List[str] = field(default_factory=list)
    test_fixtures: Optional[str] = None


class BaseIntentPlugin(BaseIntentHandler):
    """Base class for all intent plugins.

    Extends BaseIntentHandler to inherit all existing helpers:
    - build_base_query()
    - execute_aggregation()
    - create_result()
    - _apply_filter_to_query() / _apply_filter_group_to_query()
    - _apply_scope_to_query()
    - _get_filter_value() / _has_filter() / _create_filter_group()
    - get_element_provenance()
    - determine_presentation_format()
    - handle_custom_subintent()
    - _get_element_type_name()

    Each plugin overrides handler methods decorated with @sub_intent.
    The dispatcher calls these directly — no if/elif chains needed.
    """

    # Loaded by the registry from manifest.yaml
    metadata: Optional[IntentMetadata] = None

    def __init__(self):
        super().__init__()

    async def handle(
        self,
        query_plan: SingleQueryPlan,
        project: Project,
        session: AsyncSession,
        context: Optional[Dict] = None
    ) -> SingleQueryResult:
        """Auto-dispatch to the correct @sub_intent method.

        The IntentDispatcher resolves query_plan.subtype to the decorated
        method. This default implementation is used when the dispatcher
        calls plugin.handle() directly — it looks up the sub-intent
        method on this instance.
        """
        start_time = datetime.now()

        handler_method = self._find_sub_intent_handler(query_plan.subtype)

        if not handler_method:
            # Fall back to custom sub-intent handler for *.custom.* slugs
            if ".custom." in (query_plan.subtype or ""):
                logger.info(
                    f"Falling back to custom handler for '{query_plan.subtype}' "
                    f"in {self.__class__.__name__}"
                )
                return await self.handle_custom_subintent(
                    query_plan, project, session, context
                )
            raise RuntimeError(
                f"No handler found for sub-intent '{query_plan.subtype}' "
                f"in {self.__class__.__name__}"
            )

        result = await handler_method(query_plan, project, session, context)

        processing_time = int(
            (datetime.now() - start_time).total_seconds() * 1000
        )
        result.processing_time_ms = processing_time
        return result

    def _find_sub_intent_handler(self, sub_intent_id: str):
        """Look up the method decorated with @sub_intent for the given ID."""
        for attr_name in dir(self):
            attr = getattr(self, attr_name, None)
            if callable(attr) and hasattr(attr, "_sub_intent_id"):
                if attr._sub_intent_id == sub_intent_id:
                    return attr
        return None

    def get_registered_sub_intents(self) -> Dict[str, Any]:
        """Return a map of sub_intent_id -> bound method for all decorated methods."""
        result = {}
        for attr_name in dir(self):
            attr = getattr(self, attr_name, None)
            if callable(attr) and hasattr(attr, "_sub_intent_id"):
                result[attr._sub_intent_id] = attr
        return result