"""LQP executor: extends LegacyExecutor with LQP metamodel rewrite passes."""

from __future__ import annotations

from typing import Optional, TYPE_CHECKING

from . import rewrite as lqp_rewrite
from ...metamodel import metamodel as mm
from ..legacy_executor import LegacyExecutor

if TYPE_CHECKING:
    from ...frontend.base import Fragment


class LQPExecutor(LegacyExecutor):
    """
    LegacyExecutor variant that applies LQP rewrite passes after normalization.

    Always uses the "lqp" v0 executor. Overrides the rewrite hooks to run
    lqp_passes() on the typed+normalized v1 metamodel before v0 translation.
    """

    def execute(self, query: "Fragment", executor: Optional[str] = None, export_to="", update=False, meta=None):
        return super().execute(query, executor="lqp", export_to=export_to, update=update, meta=meta)

    def _rewrite_model(self, mm_model: mm.Model) -> mm.Model:
        for lqp_pass in lqp_rewrite.lqp_passes():
            mm_model = lqp_pass.rewrite_model(mm_model, self.config)
            assert isinstance(mm_model, mm.Model)
        return mm_model

    def _rewrite_query(self, mm_query: mm.Task) -> mm.Task:
        for lqp_pass in lqp_rewrite.lqp_passes():
            mm_query = lqp_pass.rewrite_task(mm_query, self.config)
            assert isinstance(mm_query, mm.Task)
        return mm_query
