"""Enrich OpenAPI request schemas with realistic examples for Swagger UI."""

from __future__ import annotations

from copy import deepcopy
from typing import Any
from uuid import UUID

_SAMPLE_UUID = "3fa85f64-5717-4562-b3fc-2c963f66afa6"
# Public sample speech WAV for transcription / audio-analysis Try-it-out.
_SAMPLE_AUDIO_WAV = (
    "https://www.voiptroubleshooter.com/open_speech/american/OSR_us_000_0010_8k.wav"
)
_SAMPLE_VIDEO_URL = "https://example.com/sample.mp4"
_SAMPLE_RESUME_PDF = (
    "https://raw.githubusercontent.com/Codex-Amit/Resume-parser/main/"
    "sample_resumes/Resume-1.pdf"
)

_AUDIO_SOURCE_SCHEMAS = {
    "TranscriptionRequest",
    "AudioAnalysisRequest",
}
_VOICE_SAMPLE_SCHEMAS = {
    "VoiceCloneRequest",
    "VoiceGenerateInput",
}
# Schemas that must keep interview_id in Try-it-out (required for persist/PDF).
_KEEP_INTERVIEW_ID_SCHEMAS = {
    "FinalEvaluationRequest",
    "EvaluationReportRequest",
    "FinalEvaluationStatusResponse",
}

# Always rebuild so Try-it-out stays current (most omit interview_id; see keep-set).
_FORCE_REFRESH_SCHEMAS = {
    "DocumentParseRequest",
    "FinalEvaluationRequest",
    "BadgeRecommendRequest",
    "ReferenceCheckRequest",
    "TranscriptionRequest",
    "InterviewSummarizeRequest",
    "FaceEnrollRequest",
    "FaceVerificationRequest",
    "FaceManualReviewRequest",
    "VideoIntelligenceRequest",
    "BehavioralAnalysisRequest",
    "InterviewHighlightsRequest",
    "PanelistNotesRequest",
    "EvaluationReportRequest",
    "TtsSynthesizeRequest",
    "CommunicationAnalysisRequest",
    "IdVerificationRequest",
    "SemanticSkillMatchRequest",
    "InterviewAnalyticsRequest",
    "JobCreateRequest",
    "AiGenerateRequest",
    "AiEvaluateRequest",
    "AiCodeJudgeRequest",
}

# Property-name → example value (exact / substring match later)
_EXACT: dict[str, Any] = {
    "correlation_id": _SAMPLE_UUID,
    "company_id": "co-acme-001",
    # clone_id / version_id / report_id are NOT hardcoded — paste from create / draft.
    "persona_id": "183f7121-8d2c-4782-95be-5b0d27d9f956",
    "assessment_id": "assess-001",
    "aptitude_id": "apt-001",
    "puzzle_set_id": "puzzle-001",
    "scorecard_id": "sc-001",
    "candidate_id": "cand-jane-001",
    "question_id": "q-cache-design-001",
    "challenge_id": "chal-topk-001",
    "consent_id": "consent-demo-001",
    "idempotency_key": "idem-demo-q3",
    "id_source_url": "https://example.com/sample-id.jpg",
    "name": "Acme Technical Panel",
    "candidate_name": "Jane Doe",
    "company_name": "Acme Corp",
    "expected_name": "Jane Doe",
    "voice_name": "Acme Interviewer Voice",
    "role_title": "Backend Engineer",
    "target_role": "Senior Backend Engineer",
    "subject": "System Design",
    "topic": "Distributed caching",
    "domain": "logical_reasoning",
    "seniority": "mid",
    "department": "Engineering",
    "employment_type": "full_time",
    "years_of_experience": "3-5",
    "location": "Remote (US / EU)",
    "region": "north_america",
    "niche": "B2B SaaS infrastructure",
    "id_country": "US",
    "document_type_hint": "passport",
    "expected_date_of_birth": "1994-06-15",
    "language": "en",
    "target_language": "es",
    "source_language": "en",
    "audio_mime_type": "audio/wav",
    "interview_style": "structured, probing, fair",
    "tone_notes": "Professional but friendly; avoid jargon overload.",
    "tone": "professional but approachable",
    "depth": "deep",
    "description": (
        "Structured technical interviewer focused on system design and ownership."
    ),
    "recommended_for": ["Backend Engineer", "mid", "senior"],
    "instructions": (
        "Ask clarifying questions before diving deep. Score technical depth, "
        "communication, and ownership on a 1–5 scale."
    ),
    "company_context": (
        "Acme Corp builds B2B payment APIs. Interview should emphasize "
        "reliability, API design, and on-call ownership."
    ),
    "job_description": (
        "We are hiring a Backend Engineer to design and operate APIs, "
        "data pipelines, and cloud services. Requirements: Python, SQL, "
        "distributed systems, 3+ years experience."
    ),
    "resume_text": (
        "Jane Doe\nBackend Engineer\nEmail: jane.doe@example.com\n"
        "Skills: Python, FastAPI, PostgreSQL, AWS, Redis\n"
        "Experience: 5 years building APIs and data services."
    ),
    "candidate_answer": (
        "I would introduce a cache layer with Redis, set TTLs by key type, "
        "and measure hit rate plus p99 latency before rolling out."
    ),
    "answer": (
        "I would use cache-aside with Redis, short TTLs for volatile keys, "
        "and add hit-rate plus p99 latency dashboards before full rollout."
    ),
    "question": "How would you design a cache for a high-read API?",
    "planned_question": "Walk me through how you would design rate limiting for a public API.",
    "previous_stem": "Explain how you would design a cache for a high-read API.",
    "problem_statement": (
        "Implement a function that returns the top-K most frequent words "
        "in a list of strings. Optimize for time and memory."
    ),
    "starter_code": (
        "from collections import Counter\n\n"
        "def top_k_frequent(words: list[str], k: int) -> list[str]:\n"
        "    # TODO: implement\n"
        "    return []\n"
    ),
    "candidate_code": (
        "from collections import Counter\n\n"
        "def top_k_frequent(words: list[str], k: int) -> list[str]:\n"
        "    return [w for w, _ in Counter(words).most_common(k)]\n"
    ),
    "candidate_submission": (
        "I would clarify success metrics first, segment users, run a "
        "small A/B test, then roll out with a kill switch."
    ),
    "transcript_text": (
        "I led the migration of our monolith checkout service to FastAPI "
        "microservices and reduced p99 latency by 35%."
    ),
    "transcript_excerpt": (
        "Candidate: I used Redis with a cache-aside pattern and monitored "
        "hit rate before expanding the rollout."
    ),
    "evaluation_text": (
        "Strong system-design instincts; clearly explained trade-offs and "
        "monitoring. Could go deeper on failure modes."
    ),
    "panelist_notes": (
        "Hire leaning yes. Solid communication and ownership stories. "
        "Follow up on distributed-systems depth in next round."
    ),
    "referee_relationship": "former engineering manager",
    "reason": "Candidate requested a short break; resume from last checkpoint.",
    "content": "Looking for a young ninja rockstar developer to join our tribe.",
    "text": "Welcome to the interview. Please introduce yourself.",
    "markdown": "# Backend Engineer\n\nBuild reliable APIs and services.",
    "filename": "Resume-1.pdf",
    "voice": "coral",
    "format": "mp3",
    "audio_format": "wav",
    "provider": "openai",
    "model": "gpt-4o-mini-tts",
    "kind": "mcq",
    "difficulty": "medium",
    # Must match app.schemas.questions.QuestionType / assessments.QuestionType
    "question_type": "short_answer",
    "document_type": "pdf",
    "parse_target": "resume",
    "mode": "rubric",
    # Must match app.prompts.Persona values (not display labels)
    "persona": "technical",
    "puzzle_type": "logic",
    "industry": "enterprise_saas",
    "created_by": "recruiter@acme.example",
    "consent_given": True,
    "consent_version": "v1",
    "consent_timestamp": "2026-10-22T12:00:00Z",
    "status": "succeeded",
    "context": "Candidate preparing for a backend interview loop.",
}

_TRANSCRIPT_DEFAULT: list[dict[str, Any]] = [
    {
        "turn_id": "t1",
        "role": "interviewer",
        "text": "Tell me about a hard bug you fixed.",
        "timestamp_ms": 1000,
    },
    {
        "turn_id": "t2",
        "role": "candidate",
        "text": "I traced a race in our order service and shipped a lock fix.",
        "timestamp_ms": 15000,
    },
]

_RUBRIC_LIST_DEFAULT: list[dict[str, Any]] = [
    {
        "key": "correctness",
        "label": "Technical correctness",
        "description": "Technical accuracy of the answer",
        "weight": 1.0,
    },
    {
        "key": "clarity",
        "label": "Clarity",
        "description": "Clear explanation and structure",
        "weight": 1.0,
    },
]

_RUBRIC_DICT_DEFAULT: dict[str, Any] = {
    "correctness": {"weight": 0.4, "description": "Technical accuracy"},
    "clarity": {"weight": 0.3, "description": "Clear explanation"},
    "depth": {"weight": 0.3, "description": "Depth of reasoning"},
}

_LIST_DEFAULTS: dict[str, list[Any]] = {
    "company_values": ["ownership", "clarity", "customer_focus"],
    "sample_questions": [
        "Tell me about a production incident you owned end-to-end."
    ],
    "evaluation_criteria": ["technical_depth", "communication", "ownership"],
    "skills": ["Python", "FastAPI", "PostgreSQL", "System Design"],
    "required_skills": ["Python", "SQL", "API design"],
    "criteria_hints": ["technical_depth", "problem_solving", "communication"],
    "question_types": ["short_answer"],
    "answers": [
        {
            "question_id": "q1",
            "question_text": "How would you design a cache for a high-read API?",
            "expected_answer": "cache-aside with Redis and TTLs",
            "student_answer": "Use Redis with TTL and cache-aside.",
            "max_score": 1.0,
            "rubric": ["correctness", "clarity"],
            "skills": ["caching", "Redis"],
        }
    ],
    "questions": [
        {
            "id": "q1",
            "stem": "What is cache-aside?",
            "answer": "App loads cache on miss",
        }
    ],
    "transcript": _TRANSCRIPT_DEFAULT,
    "track_results": [
        {
            "track_id": "track-backend-1",
            "status": "completed",
            "score": 0.78,
        }
    ],
    "assessment_results": [
        {"assessment_id": "assess-001", "score": 0.72, "kind": "coding"}
    ],
    "interview_scores": [
        {
            "interview_id": "int-demo-001",
            "overall_score": 0.81,
            "role_title": "Backend Engineer",
        }
    ],
    "candidates": [
        {
            "candidate_id": "cand-jane-001",
            "skills": ["Python", "FastAPI", "PostgreSQL"],
            "niche": "B2B SaaS infrastructure",
            "interview_pass_rate": 0.82,
            "task_score": 0.78,
            "badge_count": 3,
            "assessment_scores": {"aptitude": 0.8, "coding": 0.75},
        },
        {
            "candidate_id": "cand-sam-002",
            "skills": ["Python", "SQL", "AWS"],
            "niche": "B2B SaaS infrastructure",
            "interview_pass_rate": 0.71,
            "task_score": 0.69,
            "badge_count": 1,
            "assessment_scores": {"aptitude": 0.7, "coding": 0.72},
        },
    ],
    "job_catalog": [
        {
            "job_id": "job-be-001",
            "title": "Backend Engineer",
            "description": "Python APIs and data services",
            "skills": ["Python", "FastAPI", "PostgreSQL"],
            "required_skills": ["Python", "SQL"],
            "location": "Remote",
            "seniority": "mid",
            "department": "Engineering",
        },
        {
            "job_id": "job-plat-002",
            "title": "Platform Engineer",
            "description": "Infra and developer platform",
            "skills": ["Python", "AWS", "Kubernetes"],
            "location": "Hybrid",
            "seniority": "senior",
            "department": "Platform",
        },
    ],
    "existing_questions": [
        {"id": "q1", "stem": "Explain REST vs RPC.", "type": "short_answer"}
    ],
    "mandatory_question_ids": ["cq1"],
    "mandatory_topics": ["caching", "API design", "on-call"],
    "events": [
        {"type": "tab_switch", "timestamp": 12.5, "detail": "switched to another tab"}
    ],
    "dataset": [
        {"candidate_id": "c1", "score": 0.82, "group": "A"},
        {"candidate_id": "c2", "score": 0.74, "group": "B"},
    ],
    "referee_responses": [
        {
            "referee_name": "Alex Manager",
            "relationship": "former manager",
            "answers": {"reliability": "high", "teamwork": "excellent"},
        }
    ],
    "test_cases": [
        {
            "name": "basic",
            "input": {"words": ["a", "b", "a"], "k": 1},
            "expected": ["a"],
        }
    ],
    "frames": [],
    "audio_base64": None,
    "source_url": _SAMPLE_AUDIO_WAV,
    "sample_url": _SAMPLE_AUDIO_WAV,
}

_OBJECT_DEFAULTS: dict[str, dict[str, Any]] = {
    "manager_profile": {
        "name": "Alex Rivera",
        "role": "Engineering Manager",
        "department": "Platform",
        "expertise": "Distributed systems and API design",
        "interviewing_style": "structured, probing, fair",
        "tone": "professional",
        "difficulty": "medium",
        "question_types": ["behavioral", "technical"],
        "duration_minutes": 45,
    },
    "rubric": _RUBRIC_DICT_DEFAULT,
}


def _example_for_prop(
    name: str,
    prop: dict[str, Any],
    *,
    schema_name: str | None = None,
    schemas: dict[str, Any] | None = None,
) -> Any:
    # Prefer OpenAPI enum / $ref-enum over hardcoded maps (avoids invalid Try-it-out values).
    enum_vals = prop.get("enum")
    if not enum_vals and schemas:
        unwrapped = _unwrap_schema(prop, schemas)
        enum_vals = unwrapped.get("enum") if isinstance(unwrapped, dict) else None
    if enum_vals:
        # Prefer a known-good exact value when it is a legal enum member.
        if name in _EXACT and _EXACT[name] in enum_vals:
            return _EXACT[name]
        return enum_vals[0]

    # Prefer schema-aware media URLs over the generic _EXACT source_url.
    if name in {"source_url", "sample_url"}:
        if schema_name in _AUDIO_SOURCE_SCHEMAS or schema_name in _VOICE_SAMPLE_SCHEMAS:
            return _SAMPLE_AUDIO_WAV
        if name == "sample_url":
            return _SAMPLE_AUDIO_WAV
        if schema_name in {
            "VideoIntelligenceRequest",
            "FaceVerificationRequest",
            "FaceEnrollRequest",
        }:
            return _SAMPLE_VIDEO_URL
        if schema_name == "DocumentParseRequest":
            return _SAMPLE_RESUME_PDF
        if schema_name == "IdVerificationRequest" or name == "id_source_url":
            return "https://example.com/sample-id.jpg"
        if name == "source_url" and schema_name is None:
            return _SAMPLE_AUDIO_WAV

    lname = name.lower()
    typ = prop.get("type")
    any_of = prop.get("anyOf") or prop.get("oneOf") or []

    # Rubric shape differs by endpoint: list[RubricCriterion] vs dict
    if name == "rubric":
        if typ == "array" or _allows_type(any_of, "array"):
            return list(_RUBRIC_LIST_DEFAULT)
        return dict(_RUBRIC_DICT_DEFAULT)

    # custom_questions: list[str] on preview generate; list[dict] on merge
    if name == "custom_questions":
        items = prop.get("items") or {}
        if schemas:
            items = _unwrap_schema(items, schemas)
        if items.get("type") == "string":
            return [
                "Describe our on-call culture and how you would handle a Sev-1."
            ]
        return [
            {
                "id": "cq1",
                "stem": "Describe our on-call culture and how you would handle a Sev-1.",
                "mandatory": True,
            }
        ]

    # Manager-clone setup `voice` is VoiceGenerateInput (upload sample), not TTS "coral".
    if name == "voice":
        unwrapped = prop if prop.get("properties") else (
            _unwrap_schema(prop, schemas or {}) if schemas else prop
        )
        nested_props = unwrapped.get("properties") or {}
        if "voice_name" in nested_props or "sample_audio_base64" in nested_props:
            if schemas is not None:
                return build_example_from_schema(
                    unwrapped, schemas, schema_name="VoiceGenerateInput"
                )
            return {
                "voice_name": "Acme Interviewer Voice",
                "sample_url": _SAMPLE_AUDIO_WAV,
                "consent_id": "consent-demo-001",
                "sample_mime_type": "audio/wav",
            }
        return _EXACT.get("voice", "coral")

    if name == "filename" and schema_name == "KnowledgeUploadInput":
        return "manager-guide.txt"
    if name == "text" and schema_name == "KnowledgeUploadInput":
        return "Interview for ownership and concrete outcomes. Probe tradeoffs."

    if name in _EXACT and name not in {"source_url", "sample_url", "voice"}:
        # Coding judge expects a programming language, not locale "en"
        if name == "language" and schema_name == "CodingJudgeRequest":
            return "python"
        return _EXACT[name]
    if name in _LIST_DEFAULTS:
        return _LIST_DEFAULTS[name]
    if name in _OBJECT_DEFAULTS:
        return dict(_OBJECT_DEFAULTS[name])

    # Field-level examples already on schema
    if "examples" in prop and prop["examples"]:
        return prop["examples"][0]
    if "example" in prop:
        return prop["example"]
    if "default" in prop and prop["default"] is not None:
        return prop["default"]

    # UUID-ish
    if "uuid" in lname or "correlation" in lname or name.endswith("_id"):
        if typ == "string" or _allows_string(any_of):
            if name.endswith("_id") and name not in _EXACT:
                return f"demo-{name.replace('_', '-')}"
            return _SAMPLE_UUID

    if "email" in lname:
        return "recruiter@acme.example"
    if "url" in lname or lname.endswith("_uri"):
        if "audio" in lname or "sample" in lname:
            return _SAMPLE_AUDIO_WAV
        if "video" in lname:
            return _SAMPLE_VIDEO_URL
        return _SAMPLE_VIDEO_URL
    if "base64" in lname or lname.endswith("_b64"):
        return ""  # empty rather than fake binary
    if "language" in lname:
        if schema_name == "CodingJudgeRequest":
            return "python"
        return "en"
    if "minutes" in lname or lname.endswith("_seconds"):
        return 30 if "minutes" in lname else 120
    if typ == "integer" or _allows_type(any_of, "integer"):
        if "count" in lname:
            return 5
        return 1
    if typ == "number" or _allows_type(any_of, "number"):
        return 0.75
    if typ == "boolean" or _allows_type(any_of, "boolean"):
        return True if "consent" in lname else False
    if typ == "array" or _allows_type(any_of, "array"):
        items = prop.get("items") or {}
        if schemas:
            items = _unwrap_schema(items, schemas)
        if items.get("type") == "string":
            if "skill" in lname:
                return ["Python", "FastAPI"]
            return ["example"]
        # Nested object items — build one example element when properties exist
        if items.get("properties") and schemas is not None:
            return [
                build_example_from_schema(
                    items, schemas, schema_name=items.get("title")
                )
            ]
        return []
    if (typ == "object" or _allows_type(any_of, "object")) and prop.get("properties"):
        if schemas is not None:
            return build_example_from_schema(
                prop, schemas, schema_name=prop.get("title") or name
            )
        return {}
    if typ == "object" or _allows_type(any_of, "object"):
        return {}
    if typ == "string" or _allows_string(any_of):
        if "markdown" in lname or "description" in lname or "summary" in lname:
            return "Example content for Swagger Try it out."
        if "title" in lname:
            return "Backend Engineer"
        if "style" in lname:
            return "structured and fair"
        return f"example-{name}"
    # enum / const
    if "enum" in prop and prop["enum"]:
        return prop["enum"][0]
    if "const" in prop:
        return prop["const"]
    for branch in any_of:
        if isinstance(branch, dict) and branch.get("enum"):
            return branch["enum"][0]
        if isinstance(branch, dict) and "const" in branch:
            return branch["const"]
    # Known enums by field name
    if lname in {"difficulty"}:
        return "medium"
    if lname in {"document_type"}:
        return "pdf"
    if lname in {"parse_target"}:
        return "resume"
    if lname in {"mode"}:
        return "rubric"
    if lname in {"kind"}:
        return "mcq"
    if lname in {"question_type"}:
        return "short_answer"
    return None


def _allows_string(any_of: list) -> bool:
    return _allows_type(any_of, "string")


def _allows_type(any_of: list, typ: str) -> bool:
    for branch in any_of:
        if isinstance(branch, dict) and branch.get("type") == typ:
            return True
    return False


def build_example_from_schema(
    schema: dict[str, Any],
    schemas: dict[str, Any],
    *,
    schema_name: str | None = None,
) -> dict[str, Any]:
    """Build a request example object from an OpenAPI component schema."""
    schema = _unwrap_schema(schema, schemas)
    schema_name = schema_name or schema.get("title")
    # Bare object (e.g. manager-clone draft snapshot)
    if schema.get("type") == "object" and not schema.get("properties"):
        return {
            "style_summary": "Structured technical interviewer",
            "system_prompt": "You are a fair technical interviewer for Acme.",
            "notes": "Draft version snapshot",
        }
    props = schema.get("properties") or {}
    required = set(schema.get("required") or [])
    example: dict[str, Any] = {}
    # Voice cloning examples must show sample_url + consent (validators require them).
    if schema_name == "VoiceGenerateInput":
        required = required | {"voice_name", "sample_url", "consent_id", "sample_mime_type"}
    for name, prop in props.items():
        prop = _unwrap_schema(prop, schemas)
        # Most APIs omit interview_id (Platform / session-owned). Persist/PDF APIs keep it.
        if name == "interview_id" and schema_name not in _KEEP_INTERVIEW_ID_SCHEMAS:
            continue
        if name == "interview_id" and schema_name in _KEEP_INTERVIEW_ID_SCHEMAS:
            example[name] = "int-acme-jane-001"
            continue
        # Skip huge/binary-ish optionals when not required
        if name not in required and (
            "base64" in name.lower()
            or name.lower() in {"frames", "options", "audio_features"}
        ):
            continue
        val = _example_for_prop(
            name, prop, schema_name=schema_name, schemas=schemas
        )
        if val is None and name not in required:
            continue
        if val is None:
            val = "example"
        # Omit empty optional objects/arrays that often fail nested validation
        if name not in required and val in ({}, []):
            continue
        example[name] = val
    # Prefer URL sample over empty base64 for audio/transcription APIs
    if schema_name in _AUDIO_SOURCE_SCHEMAS | _VOICE_SAMPLE_SCHEMAS:
        example.pop("audio_base64", None)
        example.pop("sample_audio_base64", None)
        if "source_url" in props:
            example["source_url"] = _SAMPLE_AUDIO_WAV
        if "sample_url" in props:
            example["sample_url"] = _SAMPLE_AUDIO_WAV
    # Always omit empty options unless required
    if "options" in example and example["options"] == {} and "options" not in required:
        example.pop("options", None)
    return example


def _unwrap_schema(node: dict[str, Any], schemas: dict[str, Any]) -> dict[str, Any]:
    """Resolve $ref and anyOf/oneOf wrappers (e.g. Model | null)."""
    if not isinstance(node, dict):
        return {}
    ref = node.get("$ref")
    if ref and ref.startswith("#/components/schemas/"):
        name = ref.rsplit("/", 1)[-1]
        return deepcopy(schemas.get(name) or {})

    for key in ("anyOf", "oneOf"):
        branches = node.get(key)
        if not isinstance(branches, list):
            continue
        for branch in branches:
            if not isinstance(branch, dict):
                continue
            if branch.get("type") == "null":
                continue
            return _unwrap_schema(branch, schemas)
    return node


def _schema_example(schema: dict[str, Any]) -> Any | None:
    """Read a Schema Object example (prefer OAS/Swagger-friendly singular `example`)."""
    if "example" in schema and schema["example"] is not None:
        return schema["example"]
    examples = schema.get("examples")
    if isinstance(examples, list) and examples:
        return examples[0]
    if isinstance(examples, dict) and examples:
        # Rare non-standard map on schema — take first value/example
        first = next(iter(examples.values()))
        if isinstance(first, dict) and "value" in first:
            return first["value"]
        return first
    return None


def _set_schema_example(schema: dict[str, Any], example_obj: dict[str, Any]) -> None:
    """Store example as singular object — Swagger Editor rejects Schema.examples arrays."""
    schema.pop("examples", None)
    schema["example"] = example_obj


def _attach_body_example(body: dict[str, Any], example_obj: dict[str, Any]) -> None:
    # Media Type Object: examples must be a map of Example Objects (not an array).
    body.pop("example", None)
    body["examples"] = {
        "default": {
            "summary": "Example request",
            "value": example_obj,
        }
    }


def _example_has_null_ids(obj: Any) -> bool:
    """True if any known id field is null (Swagger then sends null → 422)."""
    if isinstance(obj, dict):
        for k, v in obj.items():
            if v is None and (k in _EXACT or k.endswith("_id")):
                return True
            if _example_has_null_ids(v):
                return True
    elif isinstance(obj, list):
        return any(_example_has_null_ids(x) for x in obj)
    return False


def _fill_null_ids(obj: Any) -> Any:
    """Replace null id-like fields with enricher defaults (recursive).

    `interview_id` is never filled — callers must use the auto-generated value
    from POST /interviews/sessions/start.
    """
    if isinstance(obj, dict):
        out: dict[str, Any] = {}
        for k, v in obj.items():
            if k == "interview_id":
                # Drop null/hardcoded placeholders; omit from examples
                if v in (None, "", "int-demo-001", "string", ":interview_id"):
                    continue
                out[k] = v
            elif v is None and k in _EXACT:
                out[k] = _EXACT[k]
            elif v is None and k.endswith("_id"):
                out[k] = _EXACT.get(k, f"demo-{k}")
            else:
                out[k] = _fill_null_ids(v)
        return out
    if isinstance(obj, list):
        return [_fill_null_ids(x) for x in obj]
    return obj


def _strip_interview_ids(obj: Any, *, also_question_id: bool = False) -> Any:
    """Remove interview_id (and optionally question_id) from example trees."""
    drop = {"interview_id"}
    if also_question_id:
        drop.add("question_id")
    if isinstance(obj, dict):
        return {
            k: _strip_interview_ids(v, also_question_id=also_question_id)
            for k, v in obj.items()
            if k not in drop
        }
    if isinstance(obj, list):
        return [
            _strip_interview_ids(x, also_question_id=also_question_id) for x in obj
        ]
    return obj


def _has_hardcoded_interview_id(obj: Any) -> bool:
    """True if example still bakes a fixed interview_id (must be stripped)."""
    if isinstance(obj, dict):
        if "interview_id" in obj:
            return True
        return any(_has_hardcoded_interview_id(v) for v in obj.values())
    if isinstance(obj, list):
        return any(_has_hardcoded_interview_id(x) for x in obj)
    return False


def _should_refresh_example(name: str | None, existing: Any) -> bool:
    if name in (
        _AUDIO_SOURCE_SCHEMAS | _VOICE_SAMPLE_SCHEMAS | _FORCE_REFRESH_SCHEMAS
    ):
        return True
    if _example_has_null_ids(existing):
        return True
    # Rebuild so we drop hardcoded interview_id from Try-it-out bodies
    # (except schemas that require interview_id for persist/PDF).
    if name in _KEEP_INTERVIEW_ID_SCHEMAS:
        return False if isinstance(existing, dict) and existing.get("interview_id") else True
    return _has_hardcoded_interview_id(existing)


def ensure_job_create_openapi_schemas(spec: dict[str, Any]) -> None:
    """Register per-action Create Job body models for OpenAPI oneOf $refs.

    ``POST /jobs`` validates bodies from ``?action=`` at runtime (Request JSON),
    so FastAPI would not otherwise emit JobDraftBody / JobRewriteBody / etc.
    """
    from app.schemas.job_descriptions import (
        JOB_CREATE_OPENAPI_EXAMPLES,
        JobDraftBody,
        JobPublishBody,
        JobRewriteBody,
        JobValidateBody,
    )

    schemas = spec.setdefault("components", {}).setdefault("schemas", {})
    for model in (JobDraftBody, JobRewriteBody, JobValidateBody, JobPublishBody):
        raw = model.model_json_schema(ref_template="#/components/schemas/{model}")
        defs = raw.pop("$defs", {}) or {}
        for def_name, def_schema in defs.items():
            schemas.setdefault(def_name, def_schema)
        # Avoid nested $defs pointer confusion
        raw.pop("definitions", None)
        schemas[model.__name__] = raw

    # Always force the named Examples dropdown (draft/rewrite/validate/publish).
    # A later enrich pass must not collapse these into a single "default".
    _force_job_create_request_examples(spec)


def force_job_create_request_examples(spec: dict[str, Any]) -> None:
    """Ensure Swagger UI shows four Create Job body examples, not one 'default'."""
    from app.schemas.job_descriptions import JOB_CREATE_OPENAPI_EXAMPLES

    post = ((spec.get("paths") or {}).get("/api/v1/jobs") or {}).get("post")
    if not isinstance(post, dict):
        return
    rb = post.setdefault("requestBody", {})
    content = rb.setdefault("content", {}).setdefault("application/json", {})
    content.pop("example", None)
    content["examples"] = deepcopy(JOB_CREATE_OPENAPI_EXAMPLES)
    # Keep oneOf body schemas for accurate per-action contracts
    content["schema"] = {
        "oneOf": [
            {"$ref": "#/components/schemas/JobDraftBody"},
            {"$ref": "#/components/schemas/JobRewriteBody"},
            {"$ref": "#/components/schemas/JobValidateBody"},
            {"$ref": "#/components/schemas/JobPublishBody"},
        ]
    }


# Back-compat alias
_force_job_create_request_examples = force_job_create_request_examples


def ensure_performance_openapi_schemas(spec: dict[str, Any]) -> None:
    """Register per-action Candidate Performance ingest bodies for OpenAPI oneOf."""
    from app.schemas.candidate_performance import (
        PERFORMANCE_INGEST_OPENAPI_EXAMPLES,
        AiPerformanceIngestBody,
        AssessmentAttemptIngestBody,
    )

    schemas = spec.setdefault("components", {}).setdefault("schemas", {})
    for model in (AiPerformanceIngestBody, AssessmentAttemptIngestBody):
        raw = model.model_json_schema(ref_template="#/components/schemas/{model}")
        defs = raw.pop("$defs", {}) or {}
        for def_name, def_schema in defs.items():
            schemas.setdefault(def_name, def_schema)
        raw.pop("definitions", None)
        schemas[model.__name__] = raw

    force_performance_ingest_request_examples(spec)


def force_performance_ingest_request_examples(spec: dict[str, Any]) -> None:
    """Ensure Swagger UI shows ai / assessments body examples on POST performance."""
    from app.schemas.candidate_performance import PERFORMANCE_INGEST_OPENAPI_EXAMPLES

    post = (
        (spec.get("paths") or {}).get(
            "/api/v1/candidates/{candidate_id}/performance"
        )
        or {}
    ).get("post")
    if not isinstance(post, dict):
        return
    rb = post.setdefault("requestBody", {})
    content = rb.setdefault("content", {}).setdefault("application/json", {})
    content.pop("example", None)
    content["examples"] = deepcopy(PERFORMANCE_INGEST_OPENAPI_EXAMPLES)
    content["schema"] = {
        "oneOf": [
            {"$ref": "#/components/schemas/AiPerformanceIngestBody"},
            {"$ref": "#/components/schemas/AssessmentAttemptIngestBody"},
        ]
    }


_AI_HUB_OPENAPI_EXAMPLES: dict[str, dict[str, Any]] = {
    "/api/v1/ai/generate": {
        "coding_challenge": {
            "summary": "Coding challenge (same body shape)",
            "value": {
                "assessment_type": "coding_challenge",
                "question_type": "mcq_and_short_answer",
                "assessment_name": "Backend Coding Screen",
                "linked_job": "job-be-001",
                "duration": 60,
                "difficulty": "moderate",
                "number_of_questions": 5,
                "passing_score": 70,
            },
        },
        "aptitude_and_reasoning": {
            "summary": "Aptitude and reasoning (same body shape)",
            "value": {
                "assessment_type": "aptitude_and_reasoning",
                "question_type": "mcq",
                "assessment_name": "Logical Reasoning Screen",
                "linked_job": "job-be-001",
                "duration": 30,
                "difficulty": "basic",
                "number_of_questions": 10,
                "passing_score": 60,
            },
        },
        "personality_eval": {
            "summary": "Personality evaluation (same body shape)",
            "value": {
                "assessment_type": "personality_eval",
                "question_type": "short_answer",
                "assessment_name": "Culture Fit",
                "linked_job": "job-be-001",
                "duration": 25,
                "difficulty": "moderate",
                "number_of_questions": 8,
                "passing_score": 50,
            },
        },
        "role_case_play": {
            "summary": "Role case play (same body shape)",
            "value": {
                "assessment_type": "role_case_play",
                "question_type": "short_answer",
                "assessment_name": "PM Case Play",
                "linked_job": "job-pm-001",
                "duration": 45,
                "difficulty": "hard",
                "number_of_questions": 5,
                "passing_score": 70,
            },
        },
    },
    "/api/v1/ai/evaluate": {
        "coding_challenge": {
            "summary": "Grade coding challenge MCQs",
            "value": {
                "assessmentId": "assess-001",
                "candidateId": "cand-jane-001",
                "submissionId": "sub-001",
                "assessmentType": "coding_challenge",
                "timeTaken": 1800,
                "passingScore": 70,
                "questions": [
                    {
                        "questionId": "q1",
                        "stem": "What does REST stand for?",
                        "answer": "A",
                        "expectedAnswer": "A",
                        "maxScore": 1,
                        "skills": ["apis"],
                    },
                    {
                        "questionId": "q2",
                        "stem": "Name a FastAPI benefit",
                        "answer": "async",
                        "expectedAnswer": "async",
                        "maxScore": 1,
                        "skills": ["Python"],
                    },
                ],
            },
        },
        "aptitude": {
            "summary": "Grade aptitude & reasoning",
            "value": {
                "assessmentId": "apt-001",
                "candidateId": "cand-jane-001",
                "assessmentType": "aptitude_and_reasoning",
                "timeTaken": 900,
                "passingScore": 60,
                "questions": [
                    {
                        "questionId": "q1",
                        "answer": "B",
                        "expectedAnswer": "B",
                        "skills": ["logic"],
                    }
                ],
            },
        },
        "personality_eval": {
            "summary": "Grade personality eval",
            "value": {
                "assessmentId": "pers-001",
                "candidateId": "cand-jane-001",
                "assessmentType": "personality_eval",
                "timeTaken": 1200,
                "passingScore": 50,
                "questions": [
                    {
                        "questionId": "q1",
                        "stem": "Describe how you handle conflict",
                        "answer": "Listen first, then align on goals",
                        "expectedAnswer": "Listen first, then align on goals",
                        "maxScore": 1,
                        "skills": ["collaboration"],
                    }
                ],
            },
        },
        "role_case_play": {
            "summary": "Grade role case play",
            "value": {
                "assessmentId": "case-001",
                "candidateId": "cand-jane-001",
                "submissionId": "sub-case-001",
                "assessmentType": "role_case_play",
                "timeTaken": 2400,
                "passingScore": 70,
                "questions": [
                    {
                        "questionId": "s1",
                        "stem": "Customer threatens churn. What do you do?",
                        "answer": "Talk to the customer and map risk",
                        "expectedAnswer": "Talk to the customer and map risk",
                        "maxScore": 1,
                    }
                ],
            },
        },
    },
    # "/api/v1/ai/code/judge": commented out — not part of Platform evaluate flow
}


def force_ai_hub_request_examples(spec: dict[str, Any]) -> None:
    """Swagger Try-it-out examples for unified /ai assessment hub."""
    paths = spec.get("paths") or {}
    for path, examples in _AI_HUB_OPENAPI_EXAMPLES.items():
        post = (paths.get(path) or {}).get("post")
        if not isinstance(post, dict):
            continue
        rb = post.setdefault("requestBody", {})
        content = rb.setdefault("content", {}).setdefault("application/json", {})
        content.pop("example", None)
        content["examples"] = deepcopy(examples)


def ensure_ai_hub_openapi_examples(spec: dict[str, Any]) -> None:
    force_ai_hub_request_examples(spec)


def force_final_evaluation_request_examples(spec: dict[str, Any]) -> None:
    """Text / voice / video Try-it-out bodies for POST /interviews/final-evaluation."""
    from app.schemas.final_evaluation import FINAL_EVALUATION_OPENAPI_EXAMPLES

    post = (
        (spec.get("paths") or {}).get("/api/v1/interviews/final-evaluation") or {}
    ).get("post")
    if not isinstance(post, dict):
        return
    rb = post.setdefault("requestBody", {})
    content = rb.setdefault("content", {}).setdefault("application/json", {})
    content.pop("example", None)
    content["examples"] = deepcopy(FINAL_EVALUATION_OPENAPI_EXAMPLES)
    schemas = (spec.get("components") or {}).get("schemas") or {}
    if "FinalEvaluationRequest" in schemas:
        _set_schema_example(
            schemas["FinalEvaluationRequest"],
            deepcopy(FINAL_EVALUATION_OPENAPI_EXAMPLES["text"]["value"]),
        )
    # Deterministic PDF body (candidate_id + interview_id only)
    pdf_post = (
        (spec.get("paths") or {}).get("/api/v1/reports/evaluation-pdf") or {}
    ).get("post")
    if isinstance(pdf_post, dict):
        pdf_rb = pdf_post.setdefault("requestBody", {})
        pdf_content = pdf_rb.setdefault("content", {}).setdefault(
            "application/json", {}
        )
        pdf_body = {
            "correlation_id": _SAMPLE_UUID,
            "candidate_id": "cand-jane-001",
            "interview_id": "int-acme-jane-001",
            "candidate_name": "Jane Doe",
        }
        pdf_content.pop("example", None)
        pdf_content["examples"] = {
            "default": {
                "summary": "PDF from completed saved evaluation",
                "value": pdf_body,
            }
        }
        if "EvaluationReportRequest" in schemas:
            _set_schema_example(schemas["EvaluationReportRequest"], deepcopy(pdf_body))


def force_workflow_questions_batch_examples(spec: dict[str, Any]) -> None:
    """Realistic Try-it-out examples for POST .../questions/batch."""
    from app.schemas.interview_workflows import WORKFLOW_QUESTIONS_BATCH_OPENAPI_EXAMPLES

    post = (
        (spec.get("paths") or {}).get(
            "/api/v1/interview-workflows/{workflow_id}/questions/batch"
        )
        or {}
    ).get("post")
    if not isinstance(post, dict):
        return
    rb = post.setdefault("requestBody", {})
    content = rb.setdefault("content", {}).setdefault("application/json", {})
    content.pop("example", None)
    content["examples"] = deepcopy(WORKFLOW_QUESTIONS_BATCH_OPENAPI_EXAMPLES)
    schemas = spec.setdefault("components", {}).setdefault("schemas", {})
    batch_schema = schemas.get("WorkflowQuestionsBatchRequest")
    if isinstance(batch_schema, dict):
        batch_schema.pop("examples", None)
        batch_schema["example"] = deepcopy(
            WORKFLOW_QUESTIONS_BATCH_OPENAPI_EXAMPLES["create_only"]["value"]
        )


def _inject_job_create_body_schemas(spec: dict[str, Any]) -> None:
    ensure_job_create_openapi_schemas(spec)
    ensure_performance_openapi_schemas(spec)
    ensure_ai_hub_openapi_examples(spec)
    force_workflow_questions_batch_examples(spec)


def enrich_openapi_examples(spec: dict[str, Any]) -> dict[str, Any]:
    """
    Attach realistic examples to every JSON requestBody and matching component schema.

    - Media Type: `examples` map (`default.value`)
    - Schema: singular `example` object (Swagger Editor requires object, not array)
    """
    out = deepcopy(spec)
    _inject_job_create_body_schemas(out)
    schemas = out.setdefault("components", {}).setdefault("schemas", {})
    # Normalize any legacy Schema.examples arrays → example objects
    for _name, schema in list(schemas.items()):
        if not isinstance(schema, dict):
            continue
        if isinstance(schema.get("examples"), list):
            if schema["examples"] and "example" not in schema:
                schema["example"] = schema["examples"][0]
            schema.pop("examples", None)
        # Repair corrupted examples that baked in null interview_id / ids
        existing = _schema_example(schema)
        if isinstance(existing, dict) and _example_has_null_ids(existing):
            if _name.endswith("Request") and not _name.startswith("Body_"):
                rebuilt = build_example_from_schema(
                    schema, schemas, schema_name=_name
                )
                if rebuilt:
                    _set_schema_example(schema, rebuilt)
                else:
                    _set_schema_example(schema, _fill_null_ids(existing))
            else:
                _set_schema_example(schema, _fill_null_ids(existing))

    for _path, methods in (out.get("paths") or {}).items():
        for _method, op in (methods or {}).items():
            if not isinstance(op, dict):
                continue
            rb = op.get("requestBody") or {}
            content = rb.get("content") or {}
            for ct, body in content.items():
                if "json" not in ct:
                    continue
                # Create Job / AI hub examples are forced at the end of enrich
                # (do not collapse into a single "Example request" / default).
                if _path in {
                    "/api/v1/jobs",
                    "/api/v1/ai/generate",
                    "/api/v1/ai/evaluate",
                }:
                    continue
                schema = body.get("schema") or {}
                unwrapped = _unwrap_schema(schema, schemas)
                ref = schema.get("$ref")
                example_obj: dict[str, Any] | None = None
                # Set in both branches; used below for InterviewSessionAnswerRequest strip.
                title: str | None = None

                # Prefer existing schema example (except audio — always refresh sample WAV)
                if ref and ref.startswith("#/components/schemas/"):
                    name = ref.rsplit("/", 1)[-1]
                    title = name
                    target = schemas.get(name) or {}
                    existing = _schema_example(target)
                    refresh = _should_refresh_example(name, existing)
                    if existing is not None and not refresh:
                        example_obj = existing  # type: ignore[assignment]
                    else:
                        example_obj = build_example_from_schema(
                            target, schemas, schema_name=name
                        )
                        if example_obj:
                            _set_schema_example(target, example_obj)
                            schemas[name] = target
                else:
                    # anyOf → concrete Request schema
                    raw_title = unwrapped.get("title") if isinstance(unwrapped, dict) else None
                    title = raw_title if isinstance(raw_title, str) else None
                    existing = (
                        _schema_example(schemas[title])
                        if title and title in schemas
                        else None
                    )
                    refresh = _should_refresh_example(title, existing)
                    if existing is not None and not refresh:
                        example_obj = existing  # type: ignore[assignment]
                    else:
                        example_obj = build_example_from_schema(
                            unwrapped or schema,
                            schemas,
                            schema_name=title,
                        )
                        # Persist onto named request schema when we resolved one
                        for branch in (schema.get("anyOf") or schema.get("oneOf") or []):
                            if isinstance(branch, dict) and branch.get("$ref"):
                                name = branch["$ref"].rsplit("/", 1)[-1]
                                if (
                                    name in schemas
                                    and (
                                        _schema_example(schemas[name]) is None
                                        or _should_refresh_example(
                                            name, _schema_example(schemas[name])
                                        )
                                    )
                                    and example_obj
                                ):
                                    _set_schema_example(schemas[name], example_obj)

                if example_obj:
                    if _example_has_null_ids(example_obj):
                        example_obj = _fill_null_ids(example_obj)
                    strip_qid = title == "InterviewSessionAnswerRequest"
                    if title not in _KEEP_INTERVIEW_ID_SCHEMAS:
                        example_obj = _strip_interview_ids(
                            example_obj, also_question_id=strip_qid
                        )
                    elif strip_qid:
                        example_obj = _strip_interview_ids(
                            example_obj, also_question_id=True
                        )
                    _attach_body_example(body, example_obj)

    # Enrich remaining *Request schemas
    for name, schema in list(schemas.items()):
        if not name.endswith("Request"):
            continue
        if name.startswith("Body_"):
            continue
        existing = _schema_example(schema)
        if existing is not None and not _should_refresh_example(name, existing):
            continue
        example_obj = build_example_from_schema(schema, schemas, schema_name=name)
        if example_obj:
            if name not in _KEEP_INTERVIEW_ID_SCHEMAS:
                example_obj = _strip_interview_ids(
                    example_obj,
                    also_question_id=(name == "InterviewSessionAnswerRequest"),
                )
            _set_schema_example(schema, example_obj)

    # Strip leftover hardcoded interview_id except persist/PDF schemas
    for _name, schema in list(schemas.items()):
        if not isinstance(schema, dict):
            continue
        if _name in _KEEP_INTERVIEW_ID_SCHEMAS:
            continue
        existing = _schema_example(schema)
        if isinstance(existing, dict) and "interview_id" in str(existing):
            _set_schema_example(
                schema,
                _strip_interview_ids(
                    existing,
                    also_question_id=(_name == "InterviewSessionAnswerRequest"),
                ),
            )

    _fix_multipart_file_bodies(out)
    _fix_path_param_examples(out)
    _ensure_parameter_descriptions(out)
    # Last step: restore Create Job + Performance + AI hub + final-eval Examples
    force_job_create_request_examples(out)
    force_performance_ingest_request_examples(out)
    force_ai_hub_request_examples(out)
    force_final_evaluation_request_examples(out)
    return out


# Swagger Try-it-out → Parameters: tester-facing copy for known names.
_PARAM_DESCRIPTIONS: dict[str, str] = {
    "X-Internal-Token": (
        "Internal gateway auth token. Use the same value as INTERNAL_API_TOKEN "
        "from the server `.env` (Authorize pre-fills this when available)."
    ),
    "X-Interview-Access-Token": (
        "Session access token from POST /interviews/sessions/start "
        "(`session_access_token`). Required for non-last sessions; "
        "Swagger `string` is ignored and the last started session is allowed."
    ),
    "X-Interview-Owner": (
        "Optional owner binding from sessions/start (`owner_id`). "
        "Must match when the session was started with an owner; "
        "Swagger `string` is treated as empty."
    ),
    "created_by": (
        "Email or user id of the actor performing this action (audit trail). "
        "Example: recruiter@acme.example."
    ),
    "target_version_id": (
        "UUID `version_id` from a prior draft/publish for this clone. "
        "Paste from POST .../version/draft — do not invent sample UUIDs."
    ),
    "interview_id": (
        "Paste `interview_id` from POST /interviews/sessions/start "
        "(omit interview_id there to auto-generate). "
        "Swagger `string` auto-uses the last started session."
    ),
    "report_id": (
        "Exact `report_id` UUID from POST /reports/evaluation-pdf "
        "(or from `download_url`). Sample/OpenAPI UUIDs return 400."
    ),
    "clone_id": (
        "Paste `clone_id` from POST /api/v1/manager-clones (auto-generated UUID). "
        "Do not use clone-acme-001 or Swagger 'string'."
    ),
    "version_id": (
        "Paste `version_id` from POST .../version/draft (auto-generated UUID). "
        "Do not use ver-acme-001 or Swagger 'string'."
    ),
}


def _ensure_parameter_descriptions(spec: dict[str, Any]) -> None:
    """Fill missing parameter descriptions so Swagger Try-it-out explains each field."""
    for _path, methods in (spec.get("paths") or {}).items():
        if not isinstance(methods, dict):
            continue
        for _method, op in methods.items():
            if not isinstance(op, dict):
                continue
            for param in op.get("parameters") or []:
                if not isinstance(param, dict):
                    continue
                name = param.get("name")
                if not name or name not in _PARAM_DESCRIPTIONS:
                    continue
                desc = _PARAM_DESCRIPTIONS[name]
                existing = (param.get("description") or "").strip()
                schema = param.get("schema") if isinstance(param.get("schema"), dict) else None
                schema_desc = (
                    (schema.get("description") or "").strip() if schema else ""
                )
                if not existing:
                    param["description"] = desc
                if schema is not None and not schema_desc:
                    schema["description"] = desc


def _clear_workflow_path_example(param: dict[str, Any], description: str) -> None:
    """Clear examples so Swagger does not bake fake IDs; describe the workflow."""
    schema = param.setdefault("schema", {})
    param.pop("example", None)
    param.pop("examples", None)
    if isinstance(schema, dict):
        schema.pop("example", None)
        schema.pop("examples", None)
        schema.setdefault("type", "string")
        schema["description"] = description
    param["description"] = description


def _fix_path_param_examples(spec: dict[str, Any]) -> None:
    """Path param examples — never hardcode chained workflow IDs."""
    defaults = {
        "candidate_id": _EXACT["candidate_id"],
        "assessment_id": _EXACT["assessment_id"],
        "persona_id": _EXACT["persona_id"],
        "company_id": _EXACT["company_id"],
    }
    workflow_clears = {
        "interview_id": (
            "Paste interview_id from POST /interviews/sessions/start "
            "(omit interview_id there). Swagger default 'string' is rejected."
        ),
        "report_id": (
            "Paste report_id UUID from POST /reports/evaluation-pdf "
            "(or use download_url). Sample/OpenAPI UUIDs return 400."
        ),
        "clone_id": (
            "Paste clone_id from POST /api/v1/manager-clones (auto-generated UUID). "
            "Do not use clone-acme-001 or Swagger 'string'."
        ),
        "version_id": (
            "Paste version_id from POST .../version/draft. "
            "Do not use ver-acme-001 or Swagger 'string'."
        ),
    }
    for path, methods in (spec.get("paths") or {}).items():
        if not isinstance(methods, dict):
            continue
        for _method, op in methods.items():
            if not isinstance(op, dict):
                continue
            for param in op.get("parameters") or []:
                if not isinstance(param, dict):
                    continue
                name = param.get("name")
                schema = param.setdefault("schema", {})
                # Query target_version_id on rollback — clear sample UUID
                if param.get("in") == "query" and name == "target_version_id":
                    _clear_workflow_path_example(
                        param,
                        "UUID version_id from a prior draft/publish for this clone.",
                    )
                    continue
                if param.get("in") != "path":
                    continue
                if name in workflow_clears:
                    _clear_workflow_path_example(param, workflow_clears[name])
                    continue
                if name not in defaults:
                    continue
                ex = param.get("example")
                sex = schema.get("example") if isinstance(schema, dict) else None
                bad = (
                    ex is None
                    or sex is None
                    or str(ex).startswith(":")
                    or str(sex).startswith(":")
                    or str(ex) in {"string", name}
                    or str(sex) in {"string", name}
                )
                if bad:
                    param["example"] = defaults[name]
                    if isinstance(schema, dict):
                        schema["example"] = defaults[name]
                        schema.setdefault("type", "string")


def _fix_multipart_file_bodies(spec: dict[str, Any]) -> None:
    """Inline multipart file schemas so Swagger UI shows a file picker.

    `$ref` + format:binary often renders as a text box that sends the literal
    string \"string\" → FastAPI 422 (Expected UploadFile, received str).
    """
    schemas = (spec.get("components") or {}).get("schemas") or {}
    for _path, methods in (spec.get("paths") or {}).items():
        if not isinstance(methods, dict):
            continue
        for _method, op in methods.items():
            if not isinstance(op, dict):
                continue
            content = ((op.get("requestBody") or {}).get("content") or {})
            body = content.get("multipart/form-data")
            if not isinstance(body, dict):
                continue
            schema = body.get("schema") or {}
            if "$ref" in schema:
                name = schema["$ref"].rsplit("/", 1)[-1]
                resolved = deepcopy(schemas.get(name) or {})
                if resolved:
                    body["schema"] = resolved
                    schema = resolved
            props = (schema.get("properties") or {}) if isinstance(schema, dict) else {}
            file_fields: list[str] = []
            for pname, prop in props.items():
                if not isinstance(prop, dict):
                    continue
                # Treat only real file fields as binary upload — never Form strings
                # (Swagger sends filename="blob" for octet-stream encoding → 422).
                is_file = prop.get("format") == "binary" or pname.lower() in {
                    "file",
                    "files",
                    "upload",
                    "document",
                }
                if is_file:
                    prop["type"] = "string"
                    prop["format"] = "binary"
                    prop.pop("example", None)
                    prop.pop("examples", None)
                    prop.setdefault(
                        "description",
                        "Use the file picker — do not type text (avoid sending 'string').",
                    )
                    file_fields.append(pname)
                else:
                    # Ensure text/enum/bool form fields stay text parts
                    prop.pop("format", None)
                    if prop.get("contentMediaType") == "application/octet-stream":
                        prop.pop("contentMediaType", None)
            # Never attach a JSON example for multipart file uploads
            body.pop("example", None)
            body.pop("examples", None)
            # Encoding only for binary file parts — form strings must stay text/plain
            body["encoding"] = {
                name: {"contentType": "application/octet-stream"}
                for name in file_fields
            }
