"""Internal QuestionsService.generate_from_role (used by interview-workflows)."""

from __future__ import annotations

import asyncio

import pytest

from app.prompts import Persona
from app.schemas.questions import RoleQuestionGenRequest
from app.services.screening.questions import QuestionsService

JD = (
    "Build APIs in Python/FastAPI, own PostgreSQL schema design, "
    "and mentor junior engineers on system design."
)

RESUME = """\
Alex Rivera
alex@example.com

Summary
Backend engineer focused on FastAPI and data services.

Skills
Python, FastAPI, PostgreSQL, Redis, Docker

Experience
Acme Corp — Built FastAPI payment APIs with Redis caching and PostgreSQL.

Projects
Inventory sync service using FastAPI workers and PostgreSQL CDC.
"""


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


def _from_role(**extra):
    body = {
        "role_title": "Senior Backend Engineer",
        "job_description": JD,
        "persona": Persona.TECHNICAL,
        "count": 3,
        "question_types": ["short_answer"],
        "skills": ["FastAPI", "PostgreSQL"],
        **extra,
    }
    return asyncio.run(
        QuestionsService().generate_from_role(RoleQuestionGenRequest(**body))
    )


def test_from_role_http_removed() -> None:
    from fastapi.testclient import TestClient

    from app.config import get_settings
    from app.main import app

    client = TestClient(app)
    res = client.post(
        "/api/v1/questions/from-role",
        headers={"X-Internal-Token": get_settings().internal_api_token},
        json={"role_title": "Engineer", "job_description": JD, "count": 2},
    )
    assert res.status_code == 404


def test_resume_omitted_backward_compatible() -> None:
    body = _from_role()
    assert body.status.value == "succeeded" or body.status == "succeeded"
    assert body.resume_grounded is False
    assert len(body.questions) == 3
    assert "Candidate resume" in body.prompt_preview["user"]
    assert "none" in body.prompt_preview["user"]
    assert all("your resume mentions" not in q.stem.lower() for q in body.questions)


def test_resume_provided_personalizes_questions() -> None:
    body = _from_role(resume_text=RESUME)
    assert body.resume_grounded is True
    assert "resume-grounded" in body.message
    assert len(body.questions) == 3
    user = body.prompt_preview["user"]
    assert "FastAPI" in user
    assert "Acme Corp" in user or "Inventory sync" in user
    stems = " ".join(q.stem for q in body.questions).lower()
    assert "resume" in stems or "fastapi" in stems or "acme" in stems
    assert any((q.metadata or {}).get("resume_anchor") for q in body.questions)


def test_empty_resume_treated_as_omitted() -> None:
    body = _from_role(resume_text="   ", resume_structured={})
    assert body.resume_grounded is False
    assert len(body.questions) == 3
    assert all("your resume mentions" not in q.stem.lower() for q in body.questions)


def test_structured_resume_only() -> None:
    body = _from_role(
        resume_structured={
            "skills": ["FastAPI", "PostgreSQL"],
            "experience": [{"raw": "Led FastAPI migration at Globex"}],
            "projects": [{"name": "CDC pipeline", "raw": "PostgreSQL CDC pipeline"}],
        }
    )
    assert body.resume_grounded is True
    user = body.prompt_preview["user"]
    assert "Globex" in user or "CDC" in user or "FastAPI" in user


def test_ai_failure_falls_back_with_resume(monkeypatch: pytest.MonkeyPatch) -> None:
    async def fail_then_empty(*, system, user, local_factory):
        raise RuntimeError("forced failure")

    monkeypatch.setattr("app.services.screening.questions.generate_json", fail_then_empty)
    body = _from_role(resume_text=RESUME, count=2)
    assert body.status.value == "succeeded" or body.status == "succeeded"
    assert body.stub is True
    assert body.resume_grounded is True
    assert len(body.questions) == 2
    assert any("resume" in q.stem.lower() for q in body.questions)
