"""Snowflake Stream compiler — NEW capability.

Generates CREATE STREAM statements for change data capture (CDC)
on tables produced by SDK workflows.
"""

from __future__ import annotations

import logging
from typing import Any, Dict, List, Optional

from databridge_core.sdk.compiler.base import BaseCompiler
from databridge_core.sdk.core.exceptions import CompilationError
from databridge_core.sdk.core.types import CompiledArtifact

logger = logging.getLogger(__name__)


class StreamCompiler(BaseCompiler):
    """Compile CDC requirements into Snowflake Streams.

    Generates CREATE STREAM DDL for tracking changes on tables,
    typically used with Tasks for incremental processing pipelines.
    """

    object_type = "STREAM"

    def compile(
        self,
        workflow_name: str,
        params: Dict[str, Any],
        target_database: Optional[str] = None,
        target_schema: Optional[str] = None,
    ) -> List[CompiledArtifact]:
        """Compile into Snowflake Stream DDL.

        Required params:
            stream_name: Name of the stream.
            source_table: Table to track changes on.

        Optional params:
            append_only: Track only inserts (default False).
            show_initial_rows: Include existing rows (default False).
            source_type: TABLE, VIEW, or EXTERNAL TABLE (default TABLE).
            comment: DDL comment.
        """
        stream_name = params.get("stream_name")
        source_table = params.get("source_table")

        if not stream_name:
            raise CompilationError("StreamCompiler requires 'stream_name' param")
        if not source_table:
            raise CompilationError("StreamCompiler requires 'source_table' param")

        append_only = params.get("append_only", False)
        show_initial_rows = params.get("show_initial_rows", False)
        source_type = params.get("source_type", "TABLE").upper()
        comment = params.get("comment")

        fqn = self._fqn(stream_name, target_database, target_schema)
        source_fqn = self._fqn(source_table, target_database, target_schema)

        # Build DDL
        ddl_parts = [self._header(fqn)]
        ddl_parts.append(f"CREATE OR REPLACE STREAM {fqn}")
        ddl_parts.append(f"  ON {source_type} {source_fqn}")

        if append_only:
            ddl_parts.append("  APPEND_ONLY = TRUE")
        if show_initial_rows:
            ddl_parts.append("  SHOW_INITIAL_ROWS = TRUE")
        if comment:
            ddl_parts.append(f"  COMMENT = '{comment}'")

        ddl = "\n".join(ddl_parts) + ";"

        artifact = CompiledArtifact(
            artifact_type="stream",
            object_name=fqn,
            ddl=ddl,
            dependencies=[source_fqn],
            source_workflow=workflow_name,
            metadata={
                "source_table": source_fqn,
                "source_type": source_type,
                "append_only": append_only,
                "show_initial_rows": show_initial_rows,
            },
        )

        logger.info("StreamCompiler produced 1 artifact: %s", fqn)
        return [artifact]
