"""
pytest plugin for playwright-healer.

Automatically registered via the entry point:
    [project.entry-points."pytest11"]
    playwright-healer = "playwright_healer.pytest_plugin"

This plugin provides:
  • `healing_page` fixture — a HealingPage wrapping the pytest-playwright `page`
  • `healing_config` fixture — the HealerConfig (override to customise)
  • `--ph-strategy` CLI option
  • `--ph-report-dir` CLI option
  • Automatic session-end report generation

Usage in tests (no conftest needed):
  async def test_login(healing_page):
      await healing_page.goto("https://example.com")
      await healing_page.click("#submit-btn", "Submit button")
"""

from __future__ import annotations

import os
from pathlib import Path
from typing import AsyncGenerator, Generator

import pytest

from playwright_healer.auto_config import auto_config as _auto_config
from playwright_healer.config import HealerConfig, HealingStrategy
from playwright_healer.healer import HealingPage


def pytest_addoption(parser: pytest.Parser) -> None:
    group = parser.getgroup("playwright-healer", "Self-healing locator options")
    group.addoption(
        "--ph-strategy",
        default=None,
        choices=["SMART", "HEURISTIC_ONLY", "DOM_ONLY", "VISUAL_ONLY", "FULL", "PARALLEL"],
        help="playwright-healer healing strategy (default: SMART)",
    )
    group.addoption(
        "--ph-report-dir",
        default=None,
        help="Directory for playwright-healer HTML/JSON reports",
    )
    group.addoption(
        "--ph-no-heal",
        action="store_true",
        default=False,
        help="Disable all AI healing (heuristic only) — useful for debugging",
    )
    group.addoption(
        "--ph-cache-file",
        default=None,
        help="Path to the healing cache JSON file",
    )


def pytest_configure(config: pytest.Config) -> None:
    """Apply CLI options to environment before config is built."""
    strategy = config.getoption("--ph-strategy", default=None)
    if strategy:
        os.environ["PH_STRATEGY"] = strategy

    report_dir = config.getoption("--ph-report-dir", default=None)
    if report_dir:
        os.environ["PH_REPORT_DIR"] = report_dir

    cache_file = config.getoption("--ph-cache-file", default=None)
    if cache_file:
        os.environ["PH_CACHE_FILE"] = cache_file

    no_heal = config.getoption("--ph-no-heal", default=False)
    if no_heal:
        os.environ["PH_STRATEGY"] = "HEURISTIC_ONLY"


# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------

@pytest.fixture(scope="session")
def healing_config() -> HealerConfig:
    """
    Session-scoped configuration fixture.

    Override this fixture in your conftest.py to provide a custom config:

      @pytest.fixture(scope="session")
      def healing_config():
          return HealerConfig.builder()
              .add_provider(AIProviderConfig.builder()
                  .provider(AIProvider.GROQ)
                  .api_key("gsk_...")
                  .build())
              .strategy(HealingStrategy.SMART)
              .build()
    """
    try:
        from dotenv import load_dotenv
        load_dotenv()
    except ImportError:
        pass
    return _auto_config()


@pytest.fixture(scope="function")
async def healing_page(page: "Page", healing_config: HealerConfig, request: pytest.FixtureRequest) -> AsyncGenerator["HealingPage", None]:  # type: ignore[name-defined]  # noqa: F821
    """
    Function-scoped HealingPage fixture.

    Wraps the pytest-playwright `page` fixture with self-healing capabilities.
    Each test gets its own healing pipeline; reports are generated per-session.

    Usage:
      async def test_login(healing_page):
          await healing_page.goto("https://example.com")
          await healing_page.click("#login", "Login button")
    """
    test_name = request.node.name
    hp = HealingPage(page, healing_config, test_name=test_name)
    yield hp
    await hp.shutdown()
