"""Robot Framework helper for M5 ACMS pipeline smoke tests."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from cleveragents.domain.models.core.context_policy import (
    ContextView,
    ProjectContextPolicy,
)

_FIXTURES_DIR = Path(__file__).resolve().parents[1] / "features" / "fixtures" / "m5"


# ---------------------------------------------------------------------------
# Robot keywords
# ---------------------------------------------------------------------------


def load_acms_context_policy_fixture() -> dict[str, Any]:
    """Load the ACMS context policy fixture file."""
    fixture_path = _FIXTURES_DIR / "acms_context_policy.json"
    return json.loads(fixture_path.read_text(encoding="utf-8"))


def load_large_project_context_fixture() -> dict[str, Any]:
    """Load the large project context fixture file."""
    fixture_path = _FIXTURES_DIR / "large_project_context.json"
    return json.loads(fixture_path.read_text(encoding="utf-8"))


def load_context_analysis_fixture() -> dict[str, Any]:
    """Load the context analysis results fixture file."""
    fixture_path = _FIXTURES_DIR / "context_analysis_results.json"
    return json.loads(fixture_path.read_text(encoding="utf-8"))


def resolve_view_for_phase(phase: str) -> dict[str, Any]:
    """Resolve a view from an empty policy for the given phase."""
    policy = ProjectContextPolicy()
    view = policy.resolve_view(phase)
    return {
        "include_paths": view.include_paths,
        "exclude_paths": view.exclude_paths,
        "include_resources": view.include_resources,
        "exclude_resources": view.exclude_resources,
        "max_file_size": view.max_file_size,
        "max_total_size": view.max_total_size,
    }


def resolve_strategize_inheriting_default() -> dict[str, Any]:
    """Resolve strategize view that inherits from default."""
    policy = ProjectContextPolicy(
        default_view=ContextView(
            include_paths=["src/**/*.py"],
            exclude_paths=["**/__pycache__/**"],
            max_file_size=262144,
        ),
    )
    view = policy.resolve_view("strategize")
    return {
        "include_paths": view.include_paths,
        "max_file_size": view.max_file_size,
    }


def resolve_strategize_with_override() -> dict[str, Any]:
    """Resolve strategize view with explicit override."""
    policy = ProjectContextPolicy(
        default_view=ContextView(
            include_paths=["src/**/*.py"],
            max_file_size=262144,
        ),
        strategize_view=ContextView(
            include_paths=["src/**/*.py", "docs/**/*.md"],
            max_file_size=131072,
        ),
    )
    view = policy.resolve_view("strategize")
    return {
        "include_paths": view.include_paths,
        "max_file_size": view.max_file_size,
    }


def check_budget_enforcement(
    max_size: int,
    oversized_file: int,
    within_file: int,
) -> dict[str, bool]:
    """Check if files exceed or fit within file size budget."""
    view = ContextView(max_file_size=int(max_size))
    limit = view.max_file_size
    assert limit is not None
    return {
        "oversized": int(oversized_file) > limit,
        "within_budget": int(within_file) <= limit,
    }


def check_total_budget_enforcement(
    max_total: int,
    oversized_total: int,
    within_total: int,
) -> dict[str, bool]:
    """Check if aggregate context exceeds total size budget."""
    view = ContextView(max_total_size=int(max_total))
    limit = view.max_total_size
    assert limit is not None
    return {
        "oversized": int(oversized_total) > limit,
        "within_budget": int(within_total) <= limit,
    }


def attempt_resolve_invalid_phase(phase: str) -> dict[str, str]:
    """Try resolving an invalid phase and capture the error."""
    policy = ProjectContextPolicy()
    try:
        policy.resolve_view(phase)
        return {"error": "False", "message": ""}
    except ValueError as exc:
        return {"error": "True", "message": str(exc)}


def create_multi_project_context(
    count_a: int,
    count_b: int,
) -> dict[str, int]:
    """Simulate independent context for two projects."""
    proj_a = [{"path": f"src/a_{i}.py", "size": 1024} for i in range(int(count_a))]
    proj_b = [{"path": f"src/b_{i}.py", "size": 1024} for i in range(int(count_b))]
    return {
        "proj_a_count": len(proj_a),
        "proj_b_count": len(proj_b),
    }
