"""Interview creation workflow — setup → persona → questions (preview removed)."""

from __future__ import annotations

import pytest
from fastapi.testclient import TestClient

from app.config import get_settings
from app.database import SessionLocal, ensure_schema
from app.main import app
from app.models.interview_workflow import (
    InterviewWorkflowQuestionRecord,
    InterviewWorkflowRecord,
)

client = TestClient(app)
TOKEN = get_settings().internal_api_token
AUTH = {"X-Internal-Token": TOKEN, "X-Company-Id": "co-wf", "X-User-Id": "user-1"}
BASE = "/api/v1/interview-workflows"


@pytest.fixture(autouse=True)
def _clean_and_local_llm(monkeypatch: pytest.MonkeyPatch):
    ensure_schema()
    monkeypatch.setattr("app.llm._provider_available", lambda _name: False)
    db = SessionLocal()
    try:
        db.query(InterviewWorkflowQuestionRecord).delete()
        db.query(InterviewWorkflowRecord).delete()
        db.commit()
    finally:
        db.close()
    yield


def test_auth_required() -> None:
    assert client.post(BASE, json={"title": "x", "role": "y"}).status_code == 401


def test_full_workflow_happy_path() -> None:
    create = client.post(
        BASE,
        headers=AUTH,
        json={
            "title": "Backend Developer Interview",
            "role": "Backend Developer",
            "skills": ["Node.js", "SQL", "REST APIs"],
            "experienceLevel": "Mid-level",
            "durationMinutes": 30,
            "language": "English",
            "difficulty": "Medium",
            "mode": "video",
        },
    )
    assert create.status_code == 200, create.text
    body = create.json()
    assert body["workflowId"]
    assert body["interviewId"]
    assert body["status"] == "draft"
    wid = body["workflowId"]

    gen = client.post(
        f"{BASE}/{wid}/questions/generate",
        headers=AUTH,
        json={
            "personaId": "technical",
            "questionCount": 5,
            "questionTypes": ["technical", "scenario"],
        },
    )
    assert gen.status_code == 200, gen.text
    gen_body = gen.json()
    assert gen_body["questionCount"] >= 1
    assert gen_body["personaId"] == "technical"
    assert gen_body["status"] == "ready_for_scheduling"
    assert all("questionId" in q for q in gen_body["questions"])

    # custom question via batch create
    add = client.post(
        f"{BASE}/{wid}/questions/batch",
        headers=AUTH,
        json={
            "create": [
                {
                    "text": "Describe a time you improved API latency.",
                    "category": "Collaboration",
                    "difficulty": "medium",
                    "responseFormat": "text",
                    "responseTimeSeconds": 300,
                }
            ]
        },
    )
    assert add.status_code == 200, add.text
    custom = next(q for q in add.json()["questions"] if q["source"] == "custom")
    qid = custom["questionId"]

    edited = client.post(
        f"{BASE}/{wid}/questions/batch",
        headers=AUTH,
        json={
            "update": [
                {
                    "questionId": qid,
                    "text": "Describe a time you reduced p95 latency.",
                }
            ]
        },
    )
    assert edited.status_code == 200
    assert any("reduced p95" in q["text"] for q in edited.json()["questions"])

    # preview removed
    assert (
        client.post(
            f"{BASE}/{wid}/preview",
            headers=AUTH,
            json={"validate": True},
        ).status_code
        == 404
    )

    deleted = client.post(
        f"{BASE}/{wid}/questions/batch",
        headers=AUTH,
        json={"delete": [qid]},
    )
    assert deleted.status_code == 200
    assert all(q["questionId"] != qid for q in deleted.json()["questions"])


def test_generate_requires_persona_id() -> None:
    wid = client.post(
        BASE,
        headers=AUTH,
        json={"title": "X", "role": "Dev", "skills": ["Go"]},
    ).json()["workflowId"]
    res = client.post(
        f"{BASE}/{wid}/questions/generate",
        headers=AUTH,
        json={"questionCount": 3},
    )
    assert res.status_code == 422


def test_generate_uses_custom_persona_id() -> None:
    wid = client.post(
        BASE,
        headers=AUTH,
        json={"title": "Custom P", "role": "Engineer", "skills": ["Python"], "mode": "text"},
    ).json()["workflowId"]
    custom_id = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
    gen = client.post(
        f"{BASE}/{wid}/questions/generate",
        headers=AUTH,
        json={"personaId": custom_id, "questionCount": 3},
    )
    assert gen.status_code == 200, gen.text
    body = gen.json()
    assert body["personaId"] == custom_id
    assert body["status"] == "ready_for_scheduling"
    assert body["questionCount"] == 3


def test_questions_batch_create_update_delete_reorder() -> None:
    wid = client.post(
        BASE,
        headers=AUTH,
        json={"title": "Batch", "role": "Engineer", "skills": ["Python"], "mode": "text"},
    ).json()["workflowId"]

    created = client.post(
        f"{BASE}/{wid}/questions/batch",
        headers=AUTH,
        json={
            "create": [
                {"text": "Question alpha about Python APIs?"},
                {"text": "Question beta about databases?"},
                {"text": "Question gamma about caching?"},
            ]
        },
    )
    assert created.status_code == 200, created.text
    qs = created.json()["questions"]
    assert len(qs) == 3
    ids = [q["questionId"] for q in qs]

    mixed = client.post(
        f"{BASE}/{wid}/questions/batch",
        headers=AUTH,
        json={
            "update": [{"questionId": ids[0], "text": "Updated alpha question text?"}],
            "delete": [ids[1]],
            "create": [{"text": "Question delta about observability?"}],
            "reorder": [ids[2], ids[0]],
        },
    )
    assert mixed.status_code == 200, mixed.text
    body = mixed.json()
    texts = [q["text"] for q in body["questions"]]
    assert "Updated alpha question text?" in texts
    assert all("beta" not in t.lower() for t in texts)
    assert any("delta" in t.lower() for t in texts)
    ordered_ids = [q["questionId"] for q in body["questions"]]
    assert ordered_ids[0] == ids[2]
    assert ordered_ids[1] == ids[0]


def test_questions_batch_unknown_id_404() -> None:
    wid = client.post(
        BASE,
        headers=AUTH,
        json={"title": "X", "role": "Dev", "skills": ["Go"]},
    ).json()["workflowId"]
    res = client.post(
        f"{BASE}/{wid}/questions/batch",
        headers=AUTH,
        json={"delete": ["q-does-not-exist"]},
    )
    assert res.status_code == 404


def test_questions_batch_empty_422() -> None:
    wid = client.post(
        BASE,
        headers=AUTH,
        json={"title": "X", "role": "Dev", "skills": ["Go"]},
    ).json()["workflowId"]
    res = client.post(
        f"{BASE}/{wid}/questions/batch",
        headers=AUTH,
        json={},
    )
    assert res.status_code == 422


def test_obsolete_question_crud_routes_removed() -> None:
    wid = client.post(
        BASE,
        headers=AUTH,
        json={"title": "X", "role": "Dev", "skills": ["Go"]},
    ).json()["workflowId"]
    assert (
        client.post(
            f"{BASE}/{wid}/questions",
            headers=AUTH,
            json={"text": "Should not work anymore"},
        ).status_code
        == 404
    )
    assert (
        client.patch(
            f"{BASE}/{wid}/questions/q-x",
            headers=AUTH,
            json={"text": "nope"},
        ).status_code
        == 404
    )
    assert client.delete(f"{BASE}/{wid}/questions/q-x", headers=AUTH).status_code == 404
    assert (
        client.put(
            f"{BASE}/{wid}/questions/reorder",
            headers=AUTH,
            json={"questionIds": ["q-x"]},
        ).status_code
        == 404
    )


def test_tenant_isolation() -> None:
    create = client.post(
        BASE,
        headers=AUTH,
        json={"title": "T", "role": "Dev", "skills": ["Go"]},
    ).json()
    wid = create["workflowId"]
    other = client.get(
        f"{BASE}/{wid}",
        headers={"X-Internal-Token": TOKEN, "X-Company-Id": "co-other"},
    )
    assert other.status_code == 404


def test_swagger_placeholders_sanitized_and_generate_completes() -> None:
    create = client.post(
        BASE,
        headers={**AUTH, "X-Company-Id": "123"},
        json={
            "title": "Backend Interview",
            "role": "Backend Developer",
            "skills": ["Node.js", "SQL"],
            "experienceLevel": "example-experienceLevel",
            "durationMinutes": 30,
            "mode": "video",
            "interviewId": "123",
        },
    )
    assert create.status_code == 200, create.text
    body = create.json()
    assert body["experienceLevel"] is None
    assert body["mode"] == "video"
    assert body["interviewId"] == "123"
    wid = body["workflowId"]

    by_interview = client.get(
        f"{BASE}/123",
        headers={**AUTH, "X-Company-Id": "123"},
    )
    assert by_interview.status_code == 200
    assert by_interview.json()["workflowId"] == wid

    gen = client.post(
        f"{BASE}/123/questions/generate",
        headers={**AUTH, "X-Company-Id": "123"},
        json={
            "personaId": "technical",
            "questionCount": 5,
            "questionTypes": ["technical", "scenario"],
        },
    )
    assert gen.status_code == 200, gen.text
    gen_body = gen.json()
    assert gen_body["questionCount"] == 5
    assert gen_body["personaId"] == "technical"
    assert gen_body["status"] == "ready_for_scheduling"
    q0 = gen_body["questions"][0]
    assert q0["stem"] == q0["text"]
    assert q0["id"] == q0["questionId"]
    assert q0["evaluationCriteria"]
    assert q0["category"]
    assert q0["responseTimeSeconds"]
