from gamcp.gam_runner import execute_gam
from gamcp.tools.core import build_bulk_gam_command

def register(mcp):

    @mcp.tool()
    def bulk_process_from_sheet(
        operator_email: str,
        sheet_file_id: str,
        sheet_name: str,
        gam_command_template: list[str],
        match_field: str | None = None,
        match_pattern: str | None = None,
        redirect_to_sheet_id: str | None = None,
        redirect_to_sheet_name: str = "Bulk Output",
        confirmed: bool = False
    ) -> str:
        """
        Executes a GAM bulk command using a Google Sheet as the data source.
        
        Args:
            operator_email: The email of the admin running the command (needs access to the sheets).
            sheet_file_id: The ID of the source Google Sheet.
            sheet_name: The tab name containing the source data.
            gam_command_template: List of command template fragments using ~ColumnName syntax.
            match_field: Optional column name to filter on.
            match_pattern: Optional regex pattern to match against match_field.
            redirect_to_sheet_id: Optional Sheet ID to write results to.
            redirect_to_sheet_name: Tab name for results.
            confirmed: Must be True to execute. If False, returns a preview.
            
        GAM pattern:
            [redirect csv - multiprocess todrive tdfileid <id> tdsheet "<name>" tdupdatesheet]
            csv gsheet <operator_email> <sheet_file_id> "<sheet_name>"
            [matchfield <match_field> <match_pattern>]
            gam <gam_command_template...>
        """
        built_cmd_output = build_bulk_gam_command(
            source_type="gsheet",
            processing_mode="csv",
            gam_command_template=gam_command_template,
            operator_email=operator_email,
            sheet_file_id=sheet_file_id,
            sheet_name=sheet_name,
            match_field=match_field,
            match_pattern=match_pattern,
            redirect_to_sheet_id=redirect_to_sheet_id,
            redirect_to_sheet_name=redirect_to_sheet_name
        )
        
        if not confirmed:
            return f"PREVIEW (not executed - run with confirmed=True):\\n{built_cmd_output}"
            
        cmd_str = built_cmd_output.replace("BUILT COMMAND (not yet executed):\\n", "").strip()
        import shlex
        args = shlex.split(cmd_str)
        
        return execute_gam(args)
