from engine.effects.types import EffectConfig, EffectContext, EffectPlugin


class CropEffect(EffectPlugin):
    """Crop effect that crops the input buffer to fit the display.

    This ensures the output buffer matches the actual display dimensions,
    useful when the source produces a buffer larger than the viewport.
    """

    name = "crop"
    config = EffectConfig(enabled=True, intensity=1.0)

    def process(self, buf: list[str], ctx: EffectContext) -> list[str]:
        if not buf:
            return buf

        # Get actual display dimensions from context
        w = (
            ctx.terminal_width
            if ctx.terminal_width > 0
            else max(len(line) for line in buf)
        )
        h = ctx.terminal_height if ctx.terminal_height > 0 else len(buf)

        # Crop buffer to fit
        result = []
        for i in range(min(h, len(buf))):
            line = buf[i]
            if len(line) > w:
                result.append(line[:w])
            else:
                result.append(line + " " * (w - len(line)))

        # Pad with empty lines if needed
        while len(result) < h:
            result.append(" " * w)

        return result

    def configure(self, config: EffectConfig) -> None:
        self.config = config
