from fastapi.testclient import TestClient

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

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


def test_health() -> None:
    res = client.get("/api/v1/health")
    assert res.status_code == 200
    assert res.json()["status"] == "ok"


def test_questions_require_token() -> None:
    res = client.post(
        "/api/v1/questions/generate",
        json={"subject": "Math", "topic": "Algebra", "count": 2},
    )
    assert res.status_code == 401


def test_questions_generate() -> None:
    res = client.post(
        "/api/v1/questions/generate",
        headers=HEADERS,
        json={
            "subject": "Math",
            "topic": "Algebra",
            "count": 2,
            "question_type": "mcq",
            "difficulty": "easy",
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["status"] == "succeeded"
    assert len(body["questions"]) == 2
    assert body["questions"][0]["stem"]


def test_answers_evaluate() -> None:
    res = client.post(
        "/api/v1/answers/evaluate",
        headers=HEADERS,
        json={
            "assessment_id": "asm-1",
            "answers": [
                {
                    "question_id": "q1",
                    "question_text": "2+2?",
                    "expected_answer": "4",
                    "student_answer": "4",
                    "max_score": 1,
                }
            ],
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["assessment_id"] == "asm-1"
    assert body["max_total_score"] == 1.0
    assert body["results"]


def test_documents_parse() -> None:
    res = client.post(
        "/api/v1/documents/parse",
        headers=HEADERS,
        json={
            "document_type": "txt",
            "parse_target": "raw_text",
            "content_base64": "aGVsbG8=",
            "filename": "notes.txt",
        },
    )
    assert res.status_code == 200
    assert res.json()["status"] == "succeeded"


def test_documents_rejects_missing_source() -> None:
    res = client.post(
        "/api/v1/documents/parse",
        headers=HEADERS,
        json={"document_type": "pdf", "parse_target": "raw_text"},
    )
    assert res.status_code == 422


def test_interviewer_personas_catalog() -> None:
    res = client.get("/api/v1/personas", headers=HEADERS)
    assert res.status_code == 200
    ids = {p["id"] for p in res.json()["personas"]}
    assert {
        "technical",
        "hr_behavioral",
        "friendly_coach",
        "executive",
        "sales",
        "healthcare",
        "finance",
        "custom",
    } <= ids


def test_questions_from_role() -> None:
    res = client.post(
        "/api/v1/questions/from-role",
        headers=HEADERS,
        json={
            "role_title": "Senior Backend Engineer",
            "job_description": (
                "Build APIs in Python/FastAPI, own PostgreSQL schema design, "
                "and mentor junior engineers on system design."
            ),
            "persona": "technical",
            "count": 5,
            "question_types": ["short_answer", "coding"],
            "skills": ["FastAPI", "PostgreSQL"],
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["status"] == "succeeded"
    assert body["persona"] == "technical"
    assert len(body["questions"]) == 5
    assert "system" in body["prompt_preview"]


def test_job_descriptions_draft() -> None:
    res = client.post(
        "/api/v1/job-descriptions/draft",
        headers=HEADERS,
        json={
            "role_title": "Product Manager",
            "persona": "hr_behavioral",
            "must_have_skills": ["roadmapping", "stakeholder management"],
            "employment_type": "full_time",
            "location": "Remote",
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["title"] == "Product Manager"
    assert body["markdown"] or body["sections"]["summary"]


def test_prep_plans() -> 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 high traffic.",
            "resume_text": "3 years FastAPI experience",
            "target_level": "intermediate",
        },
    )
    assert res.status_code == 200
    assert res.json()["plan_id"]
    assert res.json()["sections"]


def test_follow_up() -> None:
    res = client.post(
        "/api/v1/interviews/follow-up",
        headers=HEADERS,
        json={
            "interview_id": "int-1",
            "role_title": "Backend Engineer",
            "candidate_answer": "I used Redis for caching hot reads.",
            "persona": "technical",
            "mode": "chat",
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["interview_id"] == "int-1"
    assert body["follow_ups"]


def test_transcription() -> None:
    res = client.post(
        "/api/v1/transcription",
        headers=HEADERS,
        json={
            "interview_id": "int-1",
            "provider": "stub",
            "audio_base64": "AAAA",
        },
    )
    assert res.status_code == 200
    assert res.json()["text"]


def test_candidate_scoring() -> None:
    res = client.post(
        "/api/v1/candidate-scoring",
        headers=HEADERS,
        json={
            "interview_id": "int-1",
            "candidate_id": "cand-1",
            "role_title": "Backend Engineer",
            "required_skills": ["Python"],
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["candidate_id"] == "cand-1"
    assert body["confidence_score"] is not None


def test_evaluation_pdf() -> None:
    res = client.post(
        "/api/v1/reports/evaluation-pdf",
        headers=HEADERS,
        json={
            "interview_id": "int-1",
            "candidate_id": "cand-1",
            "role_title": "Backend Engineer",
        },
    )
    assert res.status_code == 200
    assert res.json()["report_id"]
    assert res.json()["summary_markdown"]


def test_job_matching() -> None:
    res = client.post(
        "/api/v1/job-matching/recommend",
        headers=HEADERS,
        json={
            "candidate_id": "cand-1",
            "skills": ["Python", "FastAPI"],
            "job_catalog": [{"job_id": "j1", "title": "Backend Engineer", "skills": ["Python"]}],
        },
    )
    assert res.status_code == 200
    assert res.json()["recommendations"]


def test_assessments_generate() -> None:
    res = client.post(
        "/api/v1/assessments/generate",
        headers=HEADERS,
        json={
            "role_title": "Backend Engineer",
            "kind": "mcq",
            "count": 5,
        },
    )
    assert res.status_code == 200
    assert len(res.json()["questions"]) == 5


def test_manager_clone() -> None:
    res = client.post(
        "/api/v1/manager-clone",
        headers=HEADERS,
        json={"company_id": "co-1", "sample_questions": ["Tell me about a failure."]},
    )
    assert res.status_code == 200
    assert res.json()["style_summary"]


def test_behavioral_analysis() -> None:
    res = client.post(
        "/api/v1/behavioral-analysis",
        headers=HEADERS,
        json={
            "interview_id": "int-1",
            "mode": "voice",
            "transcript": [
                {"turn_id": "t1", "role": "candidate", "text": "I led the migration."}
            ],
        },
    )
    assert res.status_code == 200
    assert res.json()["overall_confidence"] is not None


def test_skill_gap() -> None:
    res = client.post(
        "/api/v1/skill-gap/analyze",
        headers=HEADERS,
        json={
            "role_title": "Backend Engineer",
            "job_description": "Build APIs with Python, FastAPI, and PostgreSQL at scale.",
            "required_skills": ["Python", "FastAPI", "Kubernetes"],
            "demonstrated_skills": ["Python"],
        },
    )
    assert res.status_code == 200
    assert res.json()["gaps"]


def test_hiring_fit() -> None:
    res = client.post(
        "/api/v1/hiring-fit/predict",
        headers=HEADERS,
        json={
            "candidate_id": "cand-1",
            "role_title": "Backend Engineer",
            "required_skills": ["Python"],
            "scorecard": {"technical": 0.8, "communication": 0.75},
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["hiring_fit_score"] is not None
    assert body["passed"] is not None


def test_bias_detection() -> None:
    res = client.post(
        "/api/v1/bias-detection/analyze",
        headers=HEADERS,
        json={
            "content_type": "job_description",
            "job_description": "Looking for young blood and native speakers only.",
        },
    )
    assert res.status_code == 200
    assert res.json()["flags"]


def test_interview_preview() -> None:
    res = client.post(
        "/api/v1/interview-preview/generate",
        headers=HEADERS,
        json={
            "role_title": "Backend Engineer",
            "job_description": "Own FastAPI services and mentor juniors on design.",
            "count": 3,
            "custom_questions": ["Why our company?"],
        },
    )
    assert res.status_code == 200
    assert res.json()["preview_id"]
    assert len(res.json()["questions"]) >= 3


def test_reference_checks() -> None:
    res = client.post(
        "/api/v1/reference-checks/questionnaire",
        headers=HEADERS,
        json={
            "candidate_id": "cand-1",
            "role_title": "Backend Engineer",
            "count": 5,
        },
    )
    assert res.status_code == 200
    assert len(res.json()["questions"]) == 5


def test_case_studies() -> None:
    res = client.post(
        "/api/v1/case-studies/generate",
        headers=HEADERS,
        json={
            "role_title": "Product Manager",
            "industry": "SaaS",
            "difficulty": "medium",
        },
    )
    assert res.status_code == 200
    assert res.json()["case_id"]
    assert res.json()["scenario_markdown"]


def test_progress_analytics() -> None:
    res = client.post(
        "/api/v1/progress-analytics/analyze",
        headers=HEADERS,
        json={
            "candidate_id": "cand-1",
            "mock_history": [{"score": 0.5}, {"score": 0.7}],
        },
    )
    assert res.status_code == 200
    assert res.json()["trend"] == "improving"


def test_interview_tracks() -> None:
    res = client.post(
        "/api/v1/interview-tracks/generate",
        headers=HEADERS,
        json={
            "role_title": "Backend Engineer",
            "levels": ["beginner", "intermediate"],
            "questions_per_level": 2,
        },
    )
    assert res.status_code == 200
    assert len(res.json()["levels"]) == 2


def test_aptitude() -> None:
    res = client.post(
        "/api/v1/aptitude/generate",
        headers=HEADERS,
        json={"domain": "logical_reasoning", "count": 3},
    )
    assert res.status_code == 200
    assert len(res.json()["questions"]) == 3


def test_cultural_sensitivity() -> None:
    res = client.post(
        "/api/v1/cultural-sensitivity/adapt",
        headers=HEADERS,
        json={
            "target_language": "hi",
            "region": "IN",
            "content": "Tell me about yourself.",
        },
    )
    assert res.status_code == 200
    assert res.json()["adapted_content"]


def test_face_verification() -> None:
    res = client.post(
        "/api/v1/face-verification/verify",
        headers=HEADERS,
        json={
            "interview_id": "int-1",
            "live_image_base64": "AAAA",
            "id_image_base64": "BBBB",
        },
    )
    assert res.status_code == 200
    assert res.json()["match_score"] is not None


def test_interview_highlights() -> None:
    res = client.post(
        "/api/v1/interview-highlights/generate",
        headers=HEADERS,
        json={
            "interview_id": "int-1",
            "role_title": "Backend Engineer",
            "transcript": [
                {"turn_id": "t1", "role": "candidate", "text": "I scaled Redis."}
            ],
        },
    )
    assert res.status_code == 200
    assert res.json()["strengths"]


def test_evaluate_answer() -> None:
    res = client.post(
        "/api/v1/interviews/evaluate-answer",
        headers=HEADERS,
        json={
            "interview_id": "int-1",
            "role_title": "Backend Engineer",
            "question": "Explain caching.",
            "candidate_answer": "I used Redis for hot reads with TTL and invalidation.",
        },
    )
    assert res.status_code == 200
    assert res.json()["score"] is not None


def test_confidence_scoring() -> None:
    res = client.post(
        "/api/v1/confidence-scoring/evaluate",
        headers=HEADERS,
        json={
            "interview_id": "int-1",
            "transcript": [
                {"turn_id": "t1", "role": "candidate", "text": "I led the rollout."}
            ],
        },
    )
    assert res.status_code == 200
    assert res.json()["confidence_score"] is not None


def test_proctoring() -> None:
    res = client.post(
        "/api/v1/proctoring/analyze",
        headers=HEADERS,
        json={
            "interview_id": "int-1",
            "events": [{"event_type": "tab_switch", "count": 1}],
        },
    )
    assert res.status_code == 200
    assert res.json()["integrity_passed"] is not None


def test_coding_judge() -> None:
    res = client.post(
        "/api/v1/coding/judge",
        headers=HEADERS,
        json={
            "language": "python",
            "problem_statement": "Write a function that returns the sum of two numbers.",
            "candidate_code": "def add(a, b):\n    return a + b\n",
        },
    )
    assert res.status_code == 200
    assert res.json()["passed"] is not None


def test_resume_match() -> None:
    res = client.post(
        "/api/v1/resume-match/score",
        headers=HEADERS,
        json={
            "role_title": "Backend Engineer",
            "job_description": "Need Python FastAPI and PostgreSQL experience for APIs.",
            "resume_text": "Built FastAPI services with Python for 3 years.",
            "required_skills": ["Python", "FastAPI", "Kubernetes"],
        },
    )
    assert res.status_code == 200
    assert res.json()["match_score"] is not None


def test_badges() -> None:
    res = client.post(
        "/api/v1/badges/recommend",
        headers=HEADERS,
        json={
            "candidate_id": "cand-1",
            "interview_scores": [{"score": 0.85}],
        },
    )
    assert res.status_code == 200
    assert res.json()["earned"]


def test_id_verification() -> None:
    res = client.post(
        "/api/v1/id-verification/verify",
        headers=HEADERS,
        json={
            "interview_id": "int-1",
            "expected_name": "John Doe",
            "id_image_base64": "AAAA",
        },
    )
    assert res.status_code == 200
    assert res.json()["match_score"] is not None


def test_custom_persona() -> None:
    res = client.post(
        "/api/v1/personas/custom",
        headers=HEADERS,
        json={
            "company_id": "co-1",
            "name": "Acme Technical Panel",
            "company_values": ["ownership", "clarity"],
        },
    )
    assert res.status_code == 200
    assert res.json()["persona_id"]


def test_scorecards() -> None:
    res = client.post(
        "/api/v1/scorecards/generate",
        headers=HEADERS,
        json={"role_title": "Backend Engineer"},
    )
    assert res.status_code == 200
    assert res.json()["criteria"]


def test_interview_summarize() -> None:
    res = client.post(
        "/api/v1/interviews/summarize",
        headers=HEADERS,
        json={
            "interview_id": "int-1",
            "role_title": "Backend Engineer",
            "transcript": [{"role": "candidate", "text": "I led migrations."}],
        },
    )
    assert res.status_code == 200
    assert res.json()["summary_markdown"]


def test_dei_analytics() -> None:
    res = client.post(
        "/api/v1/dei-analytics/analyze",
        headers=HEADERS,
        json={"dataset": [{"score": 0.7}, {"score": 0.8}]},
    )
    assert res.status_code == 200
    assert res.json()["fairness_score"] is not None


def test_jd_inclusivity_rewrite() -> None:
    res = client.post(
        "/api/v1/job-descriptions/rewrite",
        headers=HEADERS,
        json={
            "role_title": "Engineer",
            "job_description": "Looking for young blood native speaker rockstar ninja engineers.",
        },
    )
    assert res.status_code == 200
    assert res.json()["rewritten_markdown"]


def test_next_question() -> None:
    res = client.post(
        "/api/v1/interviews/next-question",
        headers=HEADERS,
        json={
            "interview_id": "int-1",
            "role_title": "Backend Engineer",
            "planned_questions": ["Q1 about APIs", "Q2 about DB"],
            "asked_question_ids": [],
        },
    )
    assert res.status_code == 200
    assert res.json()["question_text"]


def test_validate_lock() -> None:
    res = client.post(
        "/api/v1/interview-preview/validate-lock",
        headers=HEADERS,
        json={
            "role_title": "Backend Engineer",
            "questions": [
                {"id": "q1", "stem": "A?"},
                {"id": "q2", "stem": "B?"},
                {"id": "q3", "stem": "C?"},
            ],
        },
    )
    assert res.status_code == 200
    assert res.json()["ready_to_lock"] is True


def test_scenarios() -> None:
    res = client.post(
        "/api/v1/scenarios/generate",
        headers=HEADERS,
        json={"role_title": "Product Manager", "count": 2},
    )
    assert res.status_code == 200
    assert len(res.json()["scenarios"]) == 2


def test_tts() -> None:
    res = client.post(
        "/api/v1/tts/synthesize",
        headers=HEADERS,
        json={"text": "Welcome to your interview."},
    )
    assert res.status_code == 200
    assert res.json()["provider"] == "local"


def test_puzzles() -> None:
    res = client.post(
        "/api/v1/puzzles/generate",
        headers=HEADERS,
        json={"puzzle_type": "logic", "count": 2},
    )
    assert res.status_code == 200
    assert len(res.json()["puzzles"]) == 2


def test_follow_up_logic() -> None:
    res = client.post(
        "/api/v1/interview-preview/define-follow-up-logic",
        headers=HEADERS,
        json={
            "role_title": "Backend Engineer",
            "questions": [{"id": "q1", "stem": "Explain REST?"}],
        },
    )
    assert res.status_code == 200
    assert res.json()["rules"]


def test_merge_custom_questions() -> None:
    res = client.post(
        "/api/v1/interview-preview/merge-custom-questions",
        headers=HEADERS,
        json={
            "role_title": "Backend Engineer",
            "existing_questions": [{"id": "q1", "stem": "A?"}],
            "custom_questions": [{"id": "cq1", "stem": "Our stack?", "mandatory": True}],
        },
    )
    assert res.status_code == 200
    body = res.json()
    assert body["added_count"] == 1
    assert "cq1" in body["mandatory_question_ids"]


def test_talent_scouting() -> None:
    res = client.post(
        "/api/v1/talent-scouting/rank",
        headers=HEADERS,
        json={
            "role_title": "Backend Engineer",
            "required_skills": ["python", "aws"],
            "candidates": [
                {
                    "candidate_id": "c1",
                    "skills": ["python", "aws"],
                    "interview_pass_rate": 0.9,
                    "badge_count": 3,
                },
                {
                    "candidate_id": "c2",
                    "skills": ["java"],
                    "interview_pass_rate": 0.5,
                    "badge_count": 0,
                },
            ],
        },
    )
    assert res.status_code == 200
    ranked = res.json()["ranked"]
    assert ranked[0]["candidate_id"] == "c1"


def test_candidate_profile_summarize() -> None:
    res = client.post(
        "/api/v1/candidate-profiles/summarize",
        headers=HEADERS,
        json={
            "candidate_id": "c1",
            "target_role": "Backend Engineer",
            "badges": ["python-advanced"],
            "interview_history": [{"score": 0.8}],
        },
    )
    assert res.status_code == 200
    assert res.json()["summary_markdown"]


def test_i18n_translate() -> None:
    res = client.post(
        "/api/v1/translate",
        headers=HEADERS,
        json={
            "target_language": "es",
            "texts": ["Tell me about a challenging project."],
        },
    )
    assert res.status_code == 200
    assert res.json()["translations"][0]["translated"]
