"""Prep-plan learning modules — 450–490 target, max 500, exactly 2 questions."""

from __future__ import annotations

import asyncio

import pytest
from fastapi.testclient import TestClient

from app.config import get_settings
from app.main import app
from app.schemas.prep_plans import (
    PREP_TOPIC_CHAR_LIMIT,
    PREP_TOPIC_QUESTION_COUNT,
    PREP_TOPIC_TARGET_MIN,
    PrepPlanRequest,
)
from app.services.screening.prep_plans import (
    PrepPlansService,
    normalize_learning_modules,
    normalize_topic,
    topic_content_char_count,
)

client = TestClient(app)
HEADERS = {"X-Internal-Token": get_settings().internal_api_token}


@pytest.fixture(autouse=True)
def _force_local(monkeypatch: pytest.MonkeyPatch):
    monkeypatch.setattr("app.llm._provider_available", lambda _name: False)


def _base_payload(**overrides):
    data = {
        "role_title": "Backend Engineer",
        "job_description": (
            "Build APIs with Python, FastAPI, PostgreSQL, and Redis for high traffic. "
            "Own latency, reliability, and code quality."
        ),
        "resume_text": "3 years Django and MySQL. Limited Redis exposure.",
        "target_level": "intermediate",
        "focus_skills": ["Redis", "FastAPI"],
    }
    data.update(overrides)
    return data


def test_topic_char_count_sums_all_fields() -> None:
    assert (
        topic_content_char_count("AB", "CD", "EF", ["GH", "IJ"])
        == 2 + 2 + 2 + 2 + 2
    )


def test_normalize_topic_requires_exactly_two_questions() -> None:
    assert (
        normalize_topic(
            {
                "topic": "Redis",
                "definition": "In-memory cache used for hot reads.",
                "real_world_example": "Cache product reads with TTL.",
                "questions": ["Q1 only?"],
                "answers": ["A1"],
            }
        )
        is None
    )


def test_normalize_topic_synthesizes_answers_when_missing() -> None:
    topic = normalize_topic(
        {
            "topic": "Redis TTL",
            "definition": (
                "Expire cache keys after a TTL to bound stale reads and memory growth "
                "in hot API paths."
            ),
            "real_world_example": (
                "Product API cache-aside with 5m TTL, stampede lock, and write invalidation."
            ),
            "questions": [
                "How do you choose TTL?",
                "What happens on stampede?",
                "How do you invalidate writes?",
            ],
        }
    )
    assert topic is not None
    assert len(topic.questions) == 2
    assert len(topic.answers) == 2
    assert topic.questions[0] == "How do you choose TTL?"
    assert all(topic.answers)


def test_normalize_topic_skips_oversized_after_refine() -> None:
    raw = {
        "topic": "System design",
        "definition": "x" * 420,
        "real_world_example": "y" * 80,
        "questions": [
            "Really very basically just describe your design?",
            "Actually essentially walk through failure modes?",
        ],
        "answers": ["Long answer one.", "Long answer two."],
    }
    # Even after filler refine, still over 500 → skip (no truncation).
    assert normalize_topic(raw) is None


def test_normalize_topic_enriches_thin_content_toward_target() -> None:
    raw = {
        "topic": "Redis",
        "definition": "In-memory cache.",
        "real_world_example": "Cache product reads.",
        "questions": ["How do you use Redis?", "What can go wrong?"],
        "answers": [
            "Explain cache-aside with TTL and metrics.",
            "Cover stampede, eviction, and invalidation.",
        ],
    }
    before = topic_content_char_count(
        raw["topic"],
        raw["definition"],
        raw["real_world_example"],
        raw["questions"],
    )
    assert before < 400
    topic = normalize_topic(raw)
    assert topic is not None
    assert len(topic.answers) == 2
    after = topic_content_char_count(
        topic.topic,
        topic.definition,
        topic.real_world_example,
        topic.questions,
    )
    assert after <= PREP_TOPIC_CHAR_LIMIT
    assert after >= before
    # Enrichment should push thin topics toward the target band when room allows.
    assert after >= PREP_TOPIC_TARGET_MIN or after > before


def test_normalize_modules_skips_invalid_keeps_valid() -> None:
    modules = normalize_learning_modules(
        [
            {
                "title": "Gaps",
                "topics": [
                    {
                        "topic": "OK",
                        "definition": (
                            "Short but useful Redis interview primer covering TTL, "
                            "eviction, and stampede control for API caching."
                        ),
                        "real_world_example": (
                            "Cache-aside on product reads with metrics and rollback."
                        ),
                        "questions": [
                            "How do you pick TTL and eviction?",
                            "How do you prevent cache stampede?",
                        ],
                        "answers": [
                            "Tie TTL to freshness SLOs and memory; monitor hit rate.",
                            "Use locking/singleflight and short negative caching.",
                        ],
                    },
                    {
                        "topic": "BAD",
                        "definition": "x" * 480,
                        "real_world_example": "y" * 40,
                        "questions": ["1?", "2?"],
                        "answers": ["a1", "a2"],
                    },
                    {
                        "topic": "ONEQ",
                        "definition": "Only one question provided here.",
                        "real_world_example": "Ex.",
                        "questions": ["A?"],
                        "answers": ["Only one answer."],
                    },
                ],
            }
        ]
    )
    assert len(modules) == 1
    assert len(modules[0].topics) == 1
    assert modules[0].topics[0].topic == "OK"


def test_http_generate_returns_modules_within_budget() -> None:
    res = client.post(
        "/api/v1/prep-plans/generate",
        headers=HEADERS,
        json=_base_payload(),
    )
    assert res.status_code == 200, res.text
    body = res.json()
    assert body["plan_id"]
    assert body["status"] == "succeeded"
    assert body["sections"]
    assert body["learning_modules"]
    assert body["skill_gaps"]
    gaps_blob = " ".join(body["skill_gaps"]).lower()
    assert "redis" in gaps_blob or "fastapi" in gaps_blob

    for module in body["learning_modules"]:
        assert module["title"]
        assert module["topics"]
        for topic in module["topics"]:
            assert len(topic["questions"]) == PREP_TOPIC_QUESTION_COUNT
            assert len(topic["answers"]) == PREP_TOPIC_QUESTION_COUNT
            assert all(topic["answers"])
            total = topic_content_char_count(
                topic["topic"],
                topic["definition"],
                topic["real_world_example"],
                topic["questions"],
            )
            assert total <= PREP_TOPIC_CHAR_LIMIT


def test_service_filters_oversized_ai_topics(monkeypatch: pytest.MonkeyPatch) -> None:
    async def _fake(*, system, user, local_factory):
        return (
            {
                "summary": "AI plan",
                "skill_gaps": ["Redis", "system design"],
                "suggested_tracks": ["intermediate-backend"],
                "sections": [
                    {"title": "Study", "items": ["Redis"], "estimated_hours": 2}
                ],
                "learning_modules": [
                    {
                        "title": "Interview topics",
                        "topics": [
                            {
                                "topic": "Fits",
                                "definition": (
                                    "Redis caching for hot reads with TTL, eviction, "
                                    "and stampede awareness in API paths."
                                ),
                                "real_world_example": (
                                    "Cache-aside product API with p95 tracking and rollback."
                                ),
                                "questions": [
                                    "How do you choose TTL?",
                                    "How do you handle stampede?",
                                ],
                                "answers": [
                                    "Match TTL to freshness SLOs and measure hit rate.",
                                    "Use singleflight/locking and warm critical keys.",
                                ],
                            },
                            {
                                "topic": "Too big",
                                "definition": "z" * 450,
                                "real_world_example": "w" * 40,
                                "questions": [
                                    "Long question one about design?",
                                    "Long question two about failures?",
                                ],
                                "answers": ["A1", "A2"],
                            },
                        ],
                    }
                ],
            },
            False,
            "test-llm",
        )

    monkeypatch.setattr(
        "app.services.screening.prep_plans.generate_json",
        _fake,
    )
    payload = PrepPlanRequest(**_base_payload())
    resp = asyncio.run(PrepPlansService().generate(payload))
    assert resp.stub is False
    assert len(resp.learning_modules) == 1
    assert len(resp.learning_modules[0].topics) == 1
    assert resp.learning_modules[0].topics[0].topic == "Fits"
    assert len(resp.learning_modules[0].topics[0].answers) == 2
    assert resp.sections
    assert resp.plan_id
    assert resp.role_title == "Backend Engineer"


def test_existing_request_schema_unchanged() -> None:
    res = client.post(
        "/api/v1/prep-plans/generate",
        headers=HEADERS,
        json={
            "role_title": "Backend Engineer",
            "job_description": "Build APIs with Python and PostgreSQL for scale.",
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert "learning_modules" in body
    assert "sections" in body
    assert "skill_gaps" in body
