from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, List, Callable, Optional
import selenium.webdriver
import logging

from athenaidx.config import Config

logger = logging.getLogger(__name__)

@dataclass
class WorkflowContext:
    config: Config
    data: list = field(default_factory=list)
    meta: dict = field(default_factory=dict)

class BaseWorkflow:
    """
    Minimal workflow orchestrator. Subclasses implement step_* methods
    and a run() that calls them in order (or relies on _steps list).
    """
    name: str = "base"

    def __init__(self, ctx: WorkflowContext):
        self.ctx = ctx
        self._steps: List[Callable[[], Any]] = []
        self._build_steps()

    def _build_steps(self) -> None:
        """Subclasses append callables to self._steps in the correct order."""
        raise NotImplementedError

    def run(self, dry_run: bool = False) -> Any:
        logger.info("Starting workflow %s (dry_run=%s)", self.name, dry_run)
        for step in self._steps:
            step_name = getattr(step, "__name__", repr(step))
            logger.debug("Running step: %s", step_name)
            if dry_run:
                logger.info("Dry run: skipping execution of %s", step_name)
                continue
            try:
                result = step()
            except Exception:
                logger.exception("Step failed: %s", step_name)
                raise
            logger.debug("Step %s result: %r", step_name, result)
        logger.info("Completed workflow %s", self.name)
        return None

    def cleanup(self) -> None:
        """Optional cleanup/rollback logic after run."""
        pass