# Path: scaffold/symphony/conductor_core/handlers/action_handler/specialists/polyglot.py
# --------------------------------------------------------------------------------------

import time
import os
from pathlib import Path
from typing import Dict, Any

from ......contracts.heresy_contracts import ArtisanHeresy, HeresySeverity
from ......contracts.symphony_contracts import Edict, ActionResult, EdictType
from ......symphony.polyglot import conduct_polyglot_rite
from ..contracts import ActionSpecialist


class PolyglotRite(ActionSpecialist):
    """
    =============================================================================
    == THE UNIVERSAL TRANSLATOR (V-Ω-POLYGLOT-BRIDGE-ULTIMA)                   ==
    =============================================================================
    LIF: 10,000,000,000

    The Ambassador to Foreign Tongues. It delegates the execution of Python, Node,
    Go, Rust, and Ruby blocks to the `scaffold.symphony.polyglot` engine.

    ### THE PANTHEON OF 12 FACULTIES:
    1.  **The Gnostic Handoff:** Passes the complete `Edict` and `Context` to the Polyglot Engine.
    2.  **The Language Diviner:** Extracts the language key from the Edict's soul.
    3.  **The Context Bridge:** Serializes the current Gnostic Variables into the foreign environment.
    4.  **The Output Capturer:** Retrieves `stdout` from the foreign rite.
    5.  **The Error Propagator:** Transmutes foreign stack traces into Scaffold Heresies.
    6.  **The Dry-Run Simulation:** Visualizes the code block without executing it.
    7.  **The Sandbox Configuration:** Passes security constraints (network/fs) to the engine.
    8.  **The Dependency Check:** Verifies the foreign runtime exists before dispatch.
    9.  **The Artifact Harvester:** Collects files generated by the foreign script.
    10. **The Return Code Analyst:** Interprets exit codes from the foreign process.
    11. **The Variable Hydrator:** Updates Gnostic State if the script requests it (via stdout hooks).
    12. **The Atomic Result:** Wraps the entire foreign lifecycle in an `ActionResult`.
    """

    def conduct(self, edict: Edict, command: str) -> ActionResult:
        """
        Conducts a polyglot rite.
        'command' here is usually the language identifier (e.g. "python").
        The actual code is in `edict.script_block`.
        """
        start_time = time.time()

        # 1. The Gaze of Simulation
        if self.handler.context_manager.conductor.is_simulation():
            lang = edict.language or "unknown"
            self.console.print(f"[dim]-- Polyglot Block ({lang}) --[/dim]")
            self.console.print(edict.script_block or "[No Content]")
            return ActionResult(
                output="[DRY-RUN] Polyglot Code Block Simulated",
                returncode=0,
                duration=0.0,
                command=f"{lang}: [Block]"
            )

        # 2. The Context Bridge
        # We export the entire variable state to the foreign runtime.
        context_snapshot = self.context.variables.copy()

        # 3. The Divine Delegation
        try:
            # We call the dedicated polyglot engine
            # It handles temp file creation, execution, and cleanup
            result = conduct_polyglot_rite(
                edict,
                context_snapshot,
                self.context.cwd
            )

            # 4. The Variable Hydrator
            # If the polyglot engine supports capturing variables back (e.g. via JSON output),
            # we would parse `result.output` here. For V1, we just return the output.

            return result

        except ArtisanHeresy as h:
            # Propagate known heresies
            raise h
        except Exception as e:
            # Wrap unknown paradoxes
            raise ArtisanHeresy(
                f"Polyglot Bridge Collapse: {e}",
                child_heresy=e,
                line_num=edict.line_num
            )