"""ASV benchmarks for LifecyclePlanRepository.

Measures create, get, list, and count performance.
"""

from __future__ import annotations

from datetime import datetime

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from cleveragents.domain.models.core.action import Action, ActionState
from cleveragents.domain.models.core.plan import (
    NamespacedName,
    PlanIdentity,
    PlanPhase,
    PlanTimestamps,
    ProcessingState,
)
from cleveragents.domain.models.core.plan import Plan as V3Plan
from cleveragents.infrastructure.database.models import Base
from cleveragents.infrastructure.database.repositories import (
    ActionRepository,
    LifecyclePlanRepository,
)

_CB32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
_bench_counter = 0


def _bench_ulid() -> str:
    global _bench_counter
    _bench_counter += 1
    n = _bench_counter
    suffix = ""
    for _ in range(8):
        suffix = _CB32[n % 32] + suffix
        n //= 32
    return f"01HGZ6FE0AQDYTR4BX{suffix}"


def _make_bench_plan(plan_id: str | None = None) -> V3Plan:
    now = datetime.now()
    return V3Plan(
        identity=PlanIdentity(plan_id=plan_id or _bench_ulid(), attempt=1),
        namespaced_name=NamespacedName(namespace="local", name="bench-plan"),
        action_name="local/bench-action",
        description="Benchmark plan",
        phase=PlanPhase("action"),
        processing_state=ProcessingState("queued"),
        strategy_actor="local/s",
        execution_actor="local/e",
        timestamps=PlanTimestamps(created_at=now, updated_at=now),
        created_by="bench",
        tags=[],
        reusable=True,
        read_only=False,
    )


class TimePlanCreate:
    """Benchmark plan creation."""

    timeout = 60

    def setup(self) -> None:
        engine = create_engine("sqlite:///:memory:")
        Base.metadata.create_all(engine)
        session = sessionmaker(bind=engine)()
        self.session = session
        factory = lambda: session  # noqa: E731
        action_repo = ActionRepository(session_factory=factory)
        action = Action(
            namespaced_name=NamespacedName(namespace="local", name="bench-action"),
            description="Benchmark action",
            long_description=None,
            definition_of_done="Done",
            strategy_actor="local/s",
            execution_actor="local/e",
            estimation_actor=None,
            review_actor=None,
            arguments=[],
            reusable=True,
            read_only=False,
            state=ActionState("available"),
            created_at=datetime.now(),
            updated_at=datetime.now(),
            created_by=None,
            tags=[],
        )
        action_repo.create(action)
        session.commit()
        self.repo = LifecyclePlanRepository(session_factory=factory)

    def time_create_single(self) -> None:
        plan = _make_bench_plan()
        self.repo.create(plan)
        self.session.commit()


class TimePlanGet:
    """Benchmark plan retrieval."""

    timeout = 60

    def setup(self) -> None:
        engine = create_engine("sqlite:///:memory:")
        Base.metadata.create_all(engine)
        session = sessionmaker(bind=engine)()
        self.session = session
        factory = lambda: session  # noqa: E731
        action_repo = ActionRepository(session_factory=factory)
        action = Action(
            namespaced_name=NamespacedName(namespace="local", name="bench-action"),
            description="Benchmark action",
            long_description=None,
            definition_of_done="Done",
            strategy_actor="local/s",
            execution_actor="local/e",
            estimation_actor=None,
            review_actor=None,
            arguments=[],
            reusable=True,
            read_only=False,
            state=ActionState("available"),
            created_at=datetime.now(),
            updated_at=datetime.now(),
            created_by=None,
            tags=[],
        )
        action_repo.create(action)
        session.commit()
        self.repo = LifecyclePlanRepository(session_factory=factory)
        self.plan_id = _bench_ulid()
        plan = _make_bench_plan(self.plan_id)
        self.repo.create(plan)
        session.commit()

    def time_get_by_id(self) -> None:
        self.repo.get(self.plan_id)


class TimePlanList:
    """Benchmark plan listing with filters."""

    timeout = 60

    def setup(self) -> None:
        engine = create_engine("sqlite:///:memory:")
        Base.metadata.create_all(engine)
        session = sessionmaker(bind=engine)()
        self.session = session
        factory = lambda: session  # noqa: E731
        action_repo = ActionRepository(session_factory=factory)
        action = Action(
            namespaced_name=NamespacedName(namespace="local", name="bench-action"),
            description="Benchmark action",
            long_description=None,
            definition_of_done="Done",
            strategy_actor="local/s",
            execution_actor="local/e",
            estimation_actor=None,
            review_actor=None,
            arguments=[],
            reusable=True,
            read_only=False,
            state=ActionState("available"),
            created_at=datetime.now(),
            updated_at=datetime.now(),
            created_by=None,
            tags=[],
        )
        action_repo.create(action)
        session.commit()
        self.repo = LifecyclePlanRepository(session_factory=factory)
        for _ in range(50):
            plan = _make_bench_plan()
            self.repo.create(plan)
        session.commit()

    def time_list_all(self) -> None:
        self.repo.list_plans()

    def time_list_with_phase_filter(self) -> None:
        self.repo.list_plans(phase="action")

    def time_count_all(self) -> None:
        self.repo.count()
