from __future__ import annotations
from typing import Any, Dict

from urarovite.validators.base import BaseValidator, ValidationResult
from urarovite.utils.sheets import bulk_rename_spreadsheets_from_range


class BulkRenameSpreadsheetsValidator(BaseValidator):
    def __init__(self) -> None:
        super().__init__(
            validator_id="bulk_rename_spreadsheets",
            name="Bulk Rename Spreadsheets",
            description="Bulk rename spreadsheet titles from a template range (A=url, B=title)",
        )

    def validate(self, sheets_service: Any, sheet_id: str, mode: str, **kwargs: Any) -> Dict[str, Any]:
        result = ValidationResult()

        template_sheet_url = kwargs.get("template_sheet_url")
        a1_range = kwargs.get("range")

        if not template_sheet_url or not a1_range:
            result.add_error("Missing template_sheet_url or range")
            result.set_automated_log("Completed with errors")
            result.add_issue(1)
            return result.to_dict()

        try:
            op = bulk_rename_spreadsheets_from_range(
                sheets_service=sheets_service,
                template_spreadsheet_url=template_sheet_url,
                range=a1_range,
            )

            if not op.get("success", False):
                failures = op.get("failures", [])
                if failures:
                    result.add_issue(len(failures))
                    
                    for failure in failures:
                        result.add_error(failure.get("error", "operation_failed"))
                else:
                    result.add_error(str(op.get("error", "operation_failed")))
                result.set_automated_log("Completed with errors")
            else:
                renamed = int(op["renamed"]) if op.get("renamed") is not None else 0
                if renamed == 0:
                    result.set_automated_log("No rows processed")
                else:
                    result.add_fix(renamed)
                    result.set_automated_log("Renamed successfully")

            return result.to_dict()
        except Exception as e:
            result.add_error(f"Unexpected error: {str(e)}")
            result.set_automated_log("Completed with errors")
            return result.to_dict()


def run(
    sheets_service: Any,
    template_sheet_url: str,
    range: str,
) -> Dict[str, Any]:
    v = BulkRenameSpreadsheetsValidator()
    return v.validate(
        sheets_service=sheets_service,
        sheet_id="",
        mode="fix",
        template_sheet_url=template_sheet_url,
        range=range,
    )


