"""Shared test-related schemas for API responses.

These models use semantic field names (test_id, product_id) for external APIs.
They are populated by transformer functions from service layer DTOs.

Models are shared between MCP tools and REST endpoints to ensure consistency.
"""

from typing import Any

from pydantic import BaseModel, Field


class TestSummary(BaseModel):
    """Summary information for a single test.

    Attributes:
        test_id: Unique test identifier (integer from API)
        title: Test title/name
        goal: Test goal/objective (optional)
        status: Current test status
        review_status: Review status (optional)
        testing_type: Type of testing (rapid, focused, coverage, usability)
        duration: Test duration in minutes (optional)
        starts_at: Test start timestamp (optional)
        ends_at: Test end timestamp (optional)
    """

    __test__ = False

    test_id: int = Field(description="Test ID (integer from API)")
    title: str = Field(description="Test title")
    goal: str | None = Field(default=None, description="Test goal/objective")
    status: str = Field(description="Test status (running, locked, archived, etc.)")
    review_status: str | None = Field(default=None, description="Review status (if applicable)")
    testing_type: str = Field(description="Testing type: rapid, focused, coverage, or usability")
    duration: int | None = Field(default=None, description="Test duration in minutes")
    starts_at: str | None = Field(default=None, description="Test start timestamp")
    ends_at: str | None = Field(default=None, description="Test end timestamp")


class ProductInfoSummary(BaseModel):
    """Product information summary."""

    id: int = Field(description="Product ID (integer from API)")
    name: str = Field(description="Product name")
    type: str = Field(description="Product type")


class PaginationInfo(BaseModel):
    """Pagination metadata for paginated responses."""

    page: int = Field(description="Current page number (1-indexed)", ge=1)
    per_page: int = Field(description="Number of items per page", ge=1)
    offset: int = Field(description="Starting offset for results (0-indexed)", ge=0)
    start_index: int = Field(
        description="Index of first item in current page (0-indexed, equals offset)", ge=0
    )
    end_index: int = Field(
        description="Index of last item in current page (0-indexed, equals offset+count-1)",
        ge=-1,  # -1 when no results
    )
    total_count: int = Field(
        description="Total number of results matching the query (across all pages)", ge=0
    )
    has_more: bool = Field(description="Whether more results may be available (heuristic)")


class ListTestsOutput(BaseModel):
    """Complete output for list_tests tool.

    This is the primary output model combining product info with
    filtered test summaries and pagination metadata.
    """

    product: ProductInfoSummary = Field(description="Product information for context")
    statuses_filter: list[str] = Field(description="Statuses that were used to filter tests")
    pagination: PaginationInfo = Field(description="Pagination metadata")
    total_tests: int = Field(description="Total number of tests returned in current page", ge=0)
    tests: list[TestSummary] = Field(description="List of test summaries")


class ProductInfo(BaseModel):
    """Product information embedded in test data."""

    id: int = Field(description="Product ID (integer from API)")
    name: str = Field(description="Product name")


class FeatureInfo(BaseModel):
    """Feature information embedded in test data."""

    id: int = Field(description="Feature ID (integer from API)")
    name: str = Field(description="Feature name")


class PlatformRequirement(BaseModel):
    """Platform requirement with OS version and allowed browsers."""

    platform: str = Field(
        description=(
            "OS platform with version and device type "
            "(e.g., 'Windows 11 (Computers)', 'iOS 17.0+ (Smartphones)')"
        )
    )
    browsers: list[str] = Field(
        description=("Allowed browsers for this platform (e.g., ['Chrome', 'Firefox', 'Safari'])")
    )


class TestDetails(BaseModel):
    """Detailed information about an exploratory test."""

    id: int = Field(description="Test ID (integer from API)")
    title: str = Field(description="Test title")
    goal: str | None = Field(default=None, description="Test goal/objective")
    testing_type: str = Field(
        description="Testing type: rapid, focused, coverage, usability, or custom",
    )
    duration: int | None = Field(default=None, description="Test duration in minutes")
    status: str = Field(
        description="Test status: locked, archived, running, review, etc.",
    )
    review_status: str | None = Field(
        default=None,
        description="Review status: review_successful, review_failed, etc.",
    )
    requirements_summary: list[PlatformRequirement] | None = Field(
        default=None,
        description="Summarized requirements with platform-browser relationships",
    )
    created_at: str | None = Field(default=None, description="Creation timestamp")
    starts_at: str | None = Field(default=None, description="Start timestamp")
    ends_at: str | None = Field(default=None, description="End timestamp")
    product: ProductInfo = Field(description="Associated product information")
    feature: FeatureInfo | None = Field(
        default=None,
        description="Associated feature information (if applicable)",
    )


class BugSummary(BaseModel):
    """Bug summary statistics for a test.

    Attributes:
        total_count: Total number of bugs found in test
        by_severity: Bug count grouped by severity level
        by_status: Bug count grouped by bug status
        by_platform: Bug distribution across platforms (OS, browser, device type)
        acceptance_rates: Quality metrics (acceptance rates, alerts) or None if no bugs
        recent_bugs: List of 3 most recent bugs with basic info
    """

    total_count: int = Field(
        description="Total number of bugs found in test",
        ge=0,
        examples=[42],
    )
    by_severity: dict[str, int] = Field(
        description="Bug count grouped by severity (critical, high, low, visual, content)",
        examples=[{"critical": 5, "high": 12, "low": 18, "visual": 4, "content": 3}],
    )
    by_status: dict[str, int] = Field(
        description=(
            "Bug count grouped by status: active_accepted (customer approved), "
            "auto_accepted (auto-approved after 10 days), total_accepted (active + auto), "
            "rejected, open (forwarded/awaiting review)"
        ),
        examples=[
            {
                "active_accepted": 28,
                "auto_accepted": 5,
                "total_accepted": 33,
                "rejected": 7,
                "open": 2,
            }
        ],
    )
    by_platform: dict[str, dict[str, int]] = Field(
        description="Platform breakdown: operating_systems, browsers, device_categories",
        examples=[
            {
                "operating_systems": {"Windows": 15, "macOS": 12, "iOS": 10, "Android": 5},
                "browsers": {"Chrome": 20, "Safari": 15, "Firefox": 7},
                "device_categories": {"Desktop": 27, "Mobile": 15},
            }
        ],
    )
    acceptance_rates: dict[str, Any] | None = Field(
        default=None,
        description="Quality metrics: active/auto/overall acceptance rates, rejection rate, alerts",
        examples=[
            {
                "active_acceptance_rate": 0.667,
                "auto_acceptance_rate": 0.152,
                "overall_acceptance_rate": 0.786,
                "rejection_rate": 0.167,
                "alerts": ["High rejection rate (>15%)"],
            }
        ],
    )
    recent_bugs: list[dict[str, Any]] = Field(
        description="3 most recent bugs with id, title, severity, status",
        max_length=3,
        examples=[
            [
                {
                    "id": 12345,
                    "title": "Login button not responsive",
                    "severity": "high",
                    "status": "open",
                },
                {
                    "id": 12344,
                    "title": "Typo in error message",
                    "severity": "content",
                    "status": "active_accepted",
                },
                {
                    "id": 12343,
                    "title": "Image not loading",
                    "severity": "visual",
                    "status": "rejected",
                },
            ]
        ],
    )


class TestStatusOutput(BaseModel):
    """Complete test status with configuration and bug summary.

    This is the primary output model for the get_test_status tool,
    combining test configuration details with aggregated bug statistics.
    """

    test: TestDetails = Field(description="Detailed test configuration and status")
    bugs: BugSummary = Field(description="Aggregated bug summary statistics")
