"""Synthetic training data generator for the ModernBERT routing classifier.

Generates labelled ``TrainingExample`` objects covering all combinations of
routing classification labels:

* complexity:  trivial / simple / moderate / complex / expert
* domain:      coding / writing / analysis / creative / chat / math / data
* quality:     low / medium / high / maximum
* privacy:     personal / private / external

Templates are varied using substitution slots so the generator can produce
many distinct examples from a smaller set of patterns.

Privacy note: All data is synthetic — no real user queries are ever used.
"""

from __future__ import annotations

import logging
import random

from llmhosts.training.curator import (  # noqa: F401 — re-exported for backwards compatibility
    COMPLEXITY_LABELS,
    DOMAIN_LABELS,
    PRIVACY_LABELS,
    QUALITY_LABELS,
    TrainingExample,
)

logger = logging.getLogger(__name__)

# ---------------------------------------------------------------------------
# Template bank: (template, complexity, domain, quality, privacy)
# Slots: {LANG}, {SUBJECT}, {LEVEL}, {FORMAT}
# ---------------------------------------------------------------------------

_LANG_CHOICES: list[str] = ["Python", "TypeScript", "Rust", "Go", "Java", "C++", "JavaScript"]
_SUBJECT_CHOICES: list[str] = ["machine learning", "data pipelines", "authentication", "billing", "search", "caching"]
_FORMAT_CHOICES: list[str] = ["a blog post", "an essay", "a report", "a summary", "a tutorial", "an article"]
_LEVEL_CHOICES: list[str] = ["beginner", "intermediate", "advanced", "expert", "professional"]

# Each entry: (template_string, complexity, domain, quality, privacy)
_TEMPLATES: list[tuple[str, str, str, str, str]] = [
    # ---- trivial / coding ----
    ("Write a hello world in {LANG}.", "trivial", "coding", "low", "external"),
    ("Print 'Hello World' using {LANG}.", "trivial", "coding", "low", "external"),
    ("Create a basic for loop in {LANG}.", "trivial", "coding", "low", "external"),
    ("What does `print()` do in Python?", "trivial", "coding", "low", "external"),
    ("Show me a simple if-else statement in {LANG}.", "trivial", "coding", "low", "external"),
    ("How do I declare a variable in {LANG}?", "trivial", "coding", "low", "external"),
    ("Write a function that returns 42 in {LANG}.", "trivial", "coding", "low", "external"),
    ("Show me a list comprehension in Python.", "trivial", "coding", "low", "external"),
    ("What is the syntax for a while loop in {LANG}?", "trivial", "coding", "low", "external"),
    ("How do I comment code in {LANG}?", "trivial", "coding", "low", "external"),
    # ---- trivial / chat ----
    ("Hi there!", "trivial", "chat", "low", "external"),
    ("Hello, how are you?", "trivial", "chat", "low", "external"),
    ("Thanks for your help!", "trivial", "chat", "low", "external"),
    ("What is your name?", "trivial", "chat", "low", "external"),
    ("Good morning!", "trivial", "chat", "low", "external"),
    ("Can you help me?", "trivial", "chat", "low", "external"),
    ("Who are you?", "trivial", "chat", "low", "external"),
    ("What day is it?", "trivial", "chat", "low", "external"),
    ("Okay, got it.", "trivial", "chat", "low", "external"),
    ("Yes or no: is Python a programming language?", "trivial", "chat", "low", "external"),
    # ---- trivial / math ----
    ("What is 2 + 2?", "trivial", "math", "low", "external"),
    ("Calculate 15% of 200.", "trivial", "math", "low", "external"),
    ("What is the square root of 144?", "trivial", "math", "low", "external"),
    ("Convert 100 Celsius to Fahrenheit.", "trivial", "math", "low", "external"),
    ("What is 7 times 8?", "trivial", "math", "low", "external"),
    ("What is 50 divided by 5?", "trivial", "math", "low", "external"),
    ("Is 17 a prime number?", "trivial", "math", "low", "external"),
    ("What is the area of a square with side 4?", "trivial", "math", "low", "external"),
    ("Round 3.7 to the nearest integer.", "trivial", "math", "low", "external"),
    ("What is 2 to the power of 10?", "trivial", "math", "low", "external"),
    # ---- trivial / writing ----
    ("Fix the typo in: 'Helo World'.", "trivial", "writing", "low", "external"),
    ("Is 'their' or 'there' correct here: 'Put it over ___ '?", "trivial", "writing", "low", "external"),
    ("Capitalise the first word of this sentence: 'the cat sat.'", "trivial", "writing", "low", "external"),
    ("Correct this sentence: 'She go to school every day.'", "trivial", "writing", "low", "external"),
    ("Give me a one-word synonym for 'happy'.", "trivial", "writing", "low", "external"),
    # ---- simple / coding ----
    ("Write a {LANG} function to reverse a string.", "simple", "coding", "low", "external"),
    ("How do I read a file line by line in {LANG}?", "simple", "coding", "low", "external"),
    ("Write a {LANG} function to check if a number is even.", "simple", "coding", "low", "external"),
    ("How do I sort a list in Python?", "simple", "coding", "low", "external"),
    ("Write a {LANG} function that sums a list of numbers.", "simple", "coding", "medium", "external"),
    ("How do I convert a string to an integer in {LANG}?", "simple", "coding", "low", "external"),
    ("Write a basic HTTP GET request in {LANG}.", "simple", "coding", "medium", "external"),
    ("How do I handle exceptions in {LANG}?", "simple", "coding", "medium", "external"),
    ("Create a dictionary mapping strings to integers in {LANG}.", "simple", "coding", "low", "external"),
    ("Write a function to check if a string is a palindrome in {LANG}.", "simple", "coding", "low", "external"),
    # ---- simple / writing ----
    ("Write a short product description for a coffee mug.", "simple", "writing", "low", "external"),
    ("Rewrite this sentence in a more formal tone: 'It's super easy to use.'", "simple", "writing", "low", "external"),
    ("Write a 3-sentence summary of climate change.", "simple", "writing", "medium", "external"),
    ("Suggest a catchy headline for an article about remote work.", "simple", "writing", "low", "external"),
    ("Write a brief thank-you email for a job interview.", "simple", "writing", "medium", "external"),
    ("Paraphrase: 'The quick brown fox jumped over the lazy dog.'", "simple", "writing", "low", "external"),
    ("Write a tweet about the benefits of exercise.", "simple", "writing", "low", "external"),
    ("Convert these bullet points into a short paragraph.", "simple", "writing", "low", "external"),
    ("Write a 50-word bio for a software engineer.", "simple", "writing", "medium", "external"),
    ("Suggest 3 blog post titles about productivity.", "simple", "writing", "low", "external"),
    # ---- simple / chat ----
    ("What is the capital of France?", "simple", "chat", "low", "external"),
    ("Who invented the telephone?", "simple", "chat", "low", "external"),
    ("What does REST stand for?", "simple", "chat", "low", "external"),
    ("Can you explain what a CPU does?", "simple", "chat", "low", "external"),
    ("What is the difference between HTTP and HTTPS?", "simple", "chat", "low", "external"),
    ("What is machine learning in simple terms?", "simple", "chat", "low", "external"),
    ("What is Docker?", "simple", "chat", "low", "external"),
    ("Explain what an API is to a non-programmer.", "simple", "chat", "low", "external"),
    ("What is the difference between a list and a tuple in Python?", "simple", "coding", "low", "external"),
    ("What does CRUD stand for?", "simple", "chat", "low", "external"),
    # ---- simple / math ----
    ("Solve: x + 5 = 12.", "simple", "math", "medium", "external"),
    ("Calculate the mean of: 3, 7, 11, 15.", "simple", "math", "low", "external"),
    ("What is 35% of 480?", "simple", "math", "low", "external"),
    ("Solve the quadratic: x^2 - 5x + 6 = 0.", "simple", "math", "medium", "external"),
    ("How many seconds are in a day?", "simple", "math", "low", "external"),
    ("What is the perimeter of a rectangle 8m by 5m?", "simple", "math", "low", "external"),
    ("Simplify the fraction 18/24.", "simple", "math", "low", "external"),
    ("What is the median of: 2, 4, 6, 8, 10?", "simple", "math", "low", "external"),
    ("Convert 0.75 to a percentage.", "simple", "math", "low", "external"),
    ("Calculate: 5! (five factorial).", "simple", "math", "low", "external"),
    # ---- moderate / coding ----
    ("Implement a binary search algorithm in {LANG}.", "moderate", "coding", "medium", "external"),
    ("Write a REST API endpoint in {LANG} that handles pagination.", "moderate", "coding", "high", "external"),
    (
        "Debug this {LANG} code: the function returns None instead of the expected value.",
        "moderate",
        "coding",
        "medium",
        "external",
    ),
    ("Implement a simple LRU cache in {LANG}.", "moderate", "coding", "high", "external"),
    ("Write unit tests for a user authentication module in {LANG}.", "moderate", "coding", "high", "external"),
    ("Refactor this Python class to use dataclasses instead of __init__.", "moderate", "coding", "medium", "external"),
    ("Write a {LANG} script to parse a JSON file and output a CSV.", "moderate", "coding", "medium", "external"),
    (
        "Implement a stack data structure with push, pop, and peek in {LANG}.",
        "moderate",
        "coding",
        "medium",
        "external",
    ),
    ("Write middleware in {LANG} to log all incoming HTTP requests.", "moderate", "coding", "high", "external"),
    (
        "Create a function that validates email addresses using regex in {LANG}.",
        "moderate",
        "coding",
        "medium",
        "external",
    ),
    # ---- moderate / analysis ----
    (
        "Compare the pros and cons of PostgreSQL vs MySQL for a SaaS product.",
        "moderate",
        "analysis",
        "medium",
        "external",
    ),
    (
        "Analyse the trade-offs between microservices and a monolith architecture.",
        "moderate",
        "analysis",
        "high",
        "external",
    ),
    ("Review this business plan and identify three potential risks.", "moderate", "analysis", "medium", "external"),
    ("Compare React vs Vue for building a dashboard application.", "moderate", "analysis", "medium", "external"),
    ("What are the advantages and disadvantages of remote work?", "moderate", "analysis", "medium", "external"),
    ("Evaluate the scalability of a pub/sub messaging pattern.", "moderate", "analysis", "high", "external"),
    ("Analyse the time complexity of the following algorithm.", "moderate", "analysis", "high", "external"),
    ("Compare REST vs GraphQL for a mobile app backend.", "moderate", "analysis", "medium", "external"),
    ("Identify three bottlenecks in this deployment pipeline.", "moderate", "analysis", "medium", "external"),
    ("Assess the security risks of storing JWTs in localStorage.", "moderate", "analysis", "high", "external"),
    # ---- moderate / writing ----
    ("Write a 500-word blog post about the benefits of TypeScript.", "moderate", "writing", "medium", "external"),
    ("Draft a professional email declining a job offer.", "moderate", "writing", "high", "external"),
    ("Write {FORMAT} explaining how containerisation works.", "moderate", "writing", "medium", "external"),
    ("Create a LinkedIn post announcing a product launch.", "moderate", "writing", "medium", "external"),
    ("Write documentation for a Python library that handles HTTP retries.", "moderate", "writing", "high", "external"),
    ("Draft a project proposal for a new internal developer tool.", "moderate", "writing", "high", "external"),
    ("Write a technical blog post explaining event-driven architecture.", "moderate", "writing", "medium", "external"),
    ("Create an onboarding guide for new engineers joining a startup.", "moderate", "writing", "high", "external"),
    ("Write a case study showcasing a successful product launch.", "moderate", "writing", "high", "external"),
    ("Draft a README for an open-source CLI tool.", "moderate", "writing", "medium", "external"),
    # ---- moderate / creative ----
    ("Write a short story about an AI that becomes sentient.", "moderate", "creative", "medium", "external"),
    ("Write a poem about open-source software.", "moderate", "creative", "medium", "external"),
    ("Brainstorm 10 unique startup ideas in the fintech space.", "moderate", "creative", "low", "external"),
    ("Write a dialogue between two developers debating tabs vs spaces.", "moderate", "creative", "medium", "external"),
    ("Create a fantasy world where computers run on magic.", "moderate", "creative", "medium", "external"),
    ("Write a satirical news article about AI replacing developers.", "moderate", "creative", "medium", "external"),
    ("Brainstorm plot ideas for a thriller novel set in Silicon Valley.", "moderate", "creative", "medium", "external"),
    ("Write a short play about the invention of the internet.", "moderate", "creative", "medium", "external"),
    (
        "Create a backstory for a fictional cybersecurity expert character.",
        "moderate",
        "creative",
        "medium",
        "external",
    ),
    ("Write song lyrics about debugging code at 2am.", "moderate", "creative", "medium", "external"),
    # ---- moderate / math ----
    ("Solve the system of equations: 2x + y = 10, x - y = 2.", "moderate", "math", "high", "external"),
    ("Derive the formula for the sum of an arithmetic series.", "moderate", "math", "high", "external"),
    ("Prove that the square root of 2 is irrational.", "moderate", "math", "high", "external"),
    ("Calculate the probability that two dice sum to 7.", "moderate", "math", "medium", "external"),
    ("Find the derivative of f(x) = 3x^3 - 5x^2 + 2x - 1.", "moderate", "math", "high", "external"),
    ("Integrate: ∫ (2x + 3) dx.", "moderate", "math", "high", "external"),
    ("Solve: log_2(x) = 5.", "moderate", "math", "medium", "external"),
    ("Calculate the eigenvalues of the matrix [[2,1],[1,3]].", "moderate", "math", "high", "external"),
    ("Show that n^2 + n is always even.", "moderate", "math", "high", "external"),
    ("Calculate the standard deviation of: 5, 10, 15, 20, 25.", "moderate", "math", "medium", "external"),
    # ---- moderate / data ----
    ("Write a pandas script to clean a CSV with missing values.", "moderate", "data", "medium", "external"),
    ("Write a SQL query to find the top 10 customers by revenue.", "moderate", "data", "medium", "external"),
    ("Create a Python script to aggregate sales data by month from a CSV.", "moderate", "data", "medium", "external"),
    ("Write a SQL JOIN query to merge orders and customers tables.", "moderate", "data", "medium", "external"),
    ("Plot a bar chart of monthly sales using matplotlib.", "moderate", "data", "medium", "external"),
    ("Transform a wide-format DataFrame to long format using pandas.", "moderate", "data", "medium", "external"),
    ("Write a SQL query to find duplicate records in a table.", "moderate", "data", "medium", "external"),
    ("Create a pivot table in pandas showing revenue by product and region.", "moderate", "data", "high", "external"),
    ("Write an ETL script to load JSON files into a SQLite database.", "moderate", "data", "high", "external"),
    ("Compute rolling average over 7 days using pandas.", "moderate", "data", "medium", "external"),
    # ---- complex / coding ----
    ("Design and implement a distributed rate limiter using Redis in {LANG}.", "complex", "coding", "high", "external"),
    ("Implement a concurrent task queue with worker pools in {LANG}.", "complex", "coding", "high", "external"),
    (
        "Write a full OAuth 2.0 authorization code flow implementation in {LANG}.",
        "complex",
        "coding",
        "maximum",
        "external",
    ),
    ("Implement a plugin architecture with runtime loading in {LANG}.", "complex", "coding", "high", "external"),
    ("Design a type-safe ORM with migrations in {LANG}.", "complex", "coding", "high", "external"),
    ("Implement WebSocket pub/sub with room management in {LANG}.", "complex", "coding", "high", "external"),
    ("Write a compiler pass for dead-code elimination in {LANG}.", "complex", "coding", "high", "external"),
    ("Implement a Raft consensus algorithm in {LANG}.", "complex", "coding", "maximum", "external"),
    ("Design a multi-tenant SaaS database schema with row-level security.", "complex", "coding", "maximum", "external"),
    ("Implement a custom memory allocator in C++.", "complex", "coding", "maximum", "external"),
    # ---- complex / analysis ----
    (
        "Conduct a comprehensive security audit of a Node.js Express application.",
        "complex",
        "analysis",
        "maximum",
        "external",
    ),
    (
        "Analyse the performance characteristics of B-tree vs LSM-tree storage engines.",
        "complex",
        "analysis",
        "high",
        "external",
    ),
    (
        "Compare and evaluate five vector database solutions for a RAG system.",
        "complex",
        "analysis",
        "high",
        "external",
    ),
    (
        "Produce a detailed trade-off analysis of CQRS + event sourcing for e-commerce.",
        "complex",
        "analysis",
        "maximum",
        "external",
    ),
    (
        "Evaluate the CAP theorem implications for a globally distributed database.",
        "complex",
        "analysis",
        "maximum",
        "external",
    ),
    (
        "Analyse the regulatory compliance implications of storing EU user data in the US.",
        "complex",
        "analysis",
        "maximum",
        "external",
    ),
    (
        "Assess the total cost of ownership of Kubernetes vs managed container services.",
        "complex",
        "analysis",
        "high",
        "external",
    ),
    ("Provide a detailed post-mortem analysis of a production outage.", "complex", "analysis", "high", "external"),
    (
        "Compare ML model serving options: TorchServe, Triton, and custom FastAPI.",
        "complex",
        "analysis",
        "high",
        "external",
    ),
    ("Analyse and optimise the query plan for a slow analytical SQL query.", "complex", "analysis", "high", "external"),
    # ---- complex / analysis / private ----
    ("Review my company's internal security policies and identify gaps.", "complex", "analysis", "maximum", "private"),
    ("Analyse this quarterly financial report and highlight risks.", "complex", "analysis", "high", "private"),
    ("Review my startup's business plan before investor presentation.", "complex", "analysis", "maximum", "private"),
    (
        "Analyse our internal API rate limiting strategy and suggest improvements.",
        "complex",
        "analysis",
        "high",
        "private",
    ),
    ("Review my team's engineering processes for inefficiencies.", "complex", "analysis", "high", "private"),
    # ---- complex / writing ----
    (
        "Write a comprehensive technical design document for a microservices migration.",
        "complex",
        "writing",
        "high",
        "external",
    ),
    ("Draft a series of 5 technical blog posts on distributed systems.", "complex", "writing", "high", "external"),
    (
        "Write an RFC for introducing GraphQL subscriptions to an existing REST API.",
        "complex",
        "writing",
        "maximum",
        "external",
    ),
    (
        "Produce a detailed incident post-mortem report suitable for stakeholders.",
        "complex",
        "writing",
        "maximum",
        "external",
    ),
    (
        "Write a comprehensive onboarding programme for a 20-person engineering team.",
        "complex",
        "writing",
        "high",
        "external",
    ),
    (
        "Draft a technical whitepaper on the design of a zero-knowledge proof system.",
        "complex",
        "writing",
        "maximum",
        "external",
    ),
    ("Write a funding proposal for an AI infrastructure startup.", "complex", "writing", "high", "external"),
    (
        "Create a comprehensive API style guide for a large engineering organization.",
        "complex",
        "writing",
        "high",
        "external",
    ),
    ("Write a graduate-level lecture series outline on compilers.", "complex", "writing", "maximum", "external"),
    ("Produce a comprehensive GDPR compliance report for a SaaS product.", "complex", "writing", "maximum", "external"),
    # ---- complex / math ----
    ("Prove the Fundamental Theorem of Calculus.", "complex", "math", "maximum", "external"),
    (
        "Derive the backpropagation equations for a multi-layer neural network.",
        "complex",
        "math",
        "maximum",
        "external",
    ),
    (
        "Solve the travelling salesman problem for 10 cities using dynamic programming.",
        "complex",
        "math",
        "high",
        "external",
    ),
    ("Derive the Navier-Stokes equations from first principles.", "complex", "math", "maximum", "external"),
    ("Prove that P ≠ NP (or explain why this is hard).", "complex", "math", "maximum", "external"),
    ("Derive the Black-Scholes option pricing formula.", "complex", "math", "maximum", "external"),
    ("Compute the Fourier transform of a Gaussian function.", "complex", "math", "high", "external"),
    ("Prove the Cauchy-Schwarz inequality for complex inner product spaces.", "complex", "math", "high", "external"),
    ("Derive the equations of general relativity in tensor notation.", "complex", "math", "maximum", "external"),
    ("Solve a system of 5 coupled ODEs using Runge-Kutta methods.", "complex", "math", "high", "external"),
    # ---- complex / personal (private) ----
    ("Analyse my medical lab results and explain what they mean.", "complex", "analysis", "maximum", "personal"),
    (
        "Review my therapy session notes and identify cognitive distortions.",
        "complex",
        "analysis",
        "maximum",
        "personal",
    ),
    ("Help me draft a response to a legal dispute I'm involved in.", "complex", "writing", "maximum", "personal"),
    (
        "Analyse my financial statements and suggest tax optimisation strategies.",
        "complex",
        "analysis",
        "maximum",
        "personal",
    ),
    ("Review my performance improvement plan and help me craft a response.", "complex", "writing", "high", "personal"),
    # ---- expert / coding ----
    (
        "Design a zero-downtime database migration strategy for a 100TB PostgreSQL database.",
        "expert",
        "coding",
        "maximum",
        "external",
    ),
    (
        "Implement a lock-free concurrent hash map in C++ with cache-line alignment.",
        "expert",
        "coding",
        "maximum",
        "external",
    ),
    ("Design a globally distributed CRDT-based collaborative editor.", "expert", "coding", "maximum", "external"),
    ("Implement a JIT compiler for a simple stack-based bytecode VM.", "expert", "coding", "maximum", "external"),
    ("Design a Byzantine fault-tolerant consensus protocol.", "expert", "coding", "maximum", "external"),
    (
        "Implement a custom network protocol with encryption and authentication.",
        "expert",
        "coding",
        "maximum",
        "external",
    ),
    ("Design and implement a distributed tracing system from scratch.", "expert", "coding", "maximum", "external"),
    ("Implement a columnar storage engine with vectorised query execution.", "expert", "coding", "maximum", "external"),
    (
        "Design a multi-region active-active database replication architecture.",
        "expert",
        "coding",
        "maximum",
        "external",
    ),
    ("Implement an actor model framework with supervision trees in {LANG}.", "expert", "coding", "maximum", "external"),
    # ---- expert / analysis ----
    (
        "Conduct a formal security threat model for a payment processing system.",
        "expert",
        "analysis",
        "maximum",
        "external",
    ),
    (
        "Analyse the algorithmic complexity of a novel graph partitioning approach.",
        "expert",
        "analysis",
        "maximum",
        "external",
    ),
    ("Design a capacity planning model for a 10x traffic increase.", "expert", "analysis", "maximum", "external"),
    (
        "Evaluate the feasibility of a real-time ML inference pipeline at 1M req/s.",
        "expert",
        "analysis",
        "maximum",
        "external",
    ),
    ("Compare RDMA vs TCP for ultra-low-latency trading systems.", "expert", "analysis", "maximum", "external"),
    (
        "Analyse the cryptographic security properties of a novel key exchange protocol.",
        "expert",
        "analysis",
        "maximum",
        "external",
    ),
    ("Evaluate distributed ML training strategies at 1000-GPU scale.", "expert", "analysis", "maximum", "external"),
    (
        "Assess the correctness of a custom consensus algorithm with formal verification.",
        "expert",
        "analysis",
        "maximum",
        "external",
    ),
    ("Analyse the economic viability of a quantum computing startup.", "expert", "analysis", "maximum", "external"),
    (
        "Review the architecture of a real-time recommendation engine serving 100M users.",
        "expert",
        "analysis",
        "maximum",
        "external",
    ),
    # ---- expert / writing ----
    (
        "Write a peer-reviewed research paper on novel LLM routing strategies.",
        "expert",
        "writing",
        "maximum",
        "external",
    ),
    ("Draft a book chapter on distributed systems consistency models.", "expert", "writing", "maximum", "external"),
    (
        "Write an IEEE conference paper on hardware-accelerated graph neural networks.",
        "expert",
        "writing",
        "maximum",
        "external",
    ),
    (
        "Produce a comprehensive security architecture document for a defence contractor.",
        "expert",
        "writing",
        "maximum",
        "external",
    ),
    (
        "Write a PhD thesis introduction on causal inference in large language models.",
        "expert",
        "writing",
        "maximum",
        "external",
    ),
    # ---- expert / personal ----
    (
        "Review my medical history and help me prepare questions for my oncologist.",
        "expert",
        "analysis",
        "maximum",
        "personal",
    ),
    (
        "Analyse my investment portfolio and optimise for tax-loss harvesting.",
        "expert",
        "analysis",
        "maximum",
        "personal",
    ),
    (
        "Help me prepare for a child custody case by reviewing my legal documents.",
        "expert",
        "writing",
        "maximum",
        "personal",
    ),
    (
        "Review my academic paper draft and suggest improvements for a top-tier venue.",
        "expert",
        "writing",
        "maximum",
        "personal",
    ),
    (
        "Analyse my company's confidential financial projections for investor readiness.",
        "expert",
        "analysis",
        "maximum",
        "personal",
    ),
    # ---- private domain queries ----
    ("Summarise the key points from my private meeting notes.", "moderate", "analysis", "high", "private"),
    ("Help me draft a confidential memo for internal circulation.", "moderate", "writing", "high", "private"),
    ("Analyse this proprietary dataset and identify trends.", "moderate", "data", "high", "private"),
    ("Review this internal API specification before we share it externally.", "moderate", "coding", "high", "private"),
    (
        "Summarise this private contract and identify any unfavourable terms.",
        "moderate",
        "analysis",
        "maximum",
        "private",
    ),
    ("Review this internal code base for security vulnerabilities.", "complex", "coding", "maximum", "private"),
    ("Analyse our proprietary sales data for Q4 patterns.", "complex", "data", "high", "private"),
    ("Help me draft a private shareholder update letter.", "complex", "writing", "high", "private"),
    ("Analyse the performance of our internal recommendation algorithm.", "complex", "analysis", "high", "private"),
    ("Review and improve our internal developer documentation.", "moderate", "writing", "medium", "private"),
]


class SyntheticDataGenerator:
    """Generates labelled synthetic training examples for the ModernBERT classifier.

    Examples are created from a bank of query templates covering all routing
    classification dimensions (complexity, domain, quality, privacy).

    Usage::

        gen = SyntheticDataGenerator()
        examples = gen.generate(n_samples=10_000, seed=42)
    """

    def generate(self, n_samples: int = 10_000, seed: int = 42) -> list[TrainingExample]:
        """Generate ``n_samples`` labelled training examples.

        Samples are drawn with replacement from the template bank, with random
        slot substitution applied for variation.  The same ``seed`` always
        produces the same sequence for reproducibility.

        Args:
            n_samples: Number of examples to generate.
            seed: Random seed for reproducibility.

        Returns:
            List of ``TrainingExample`` objects.
        """
        rng = random.Random(seed)
        examples: list[TrainingExample] = []

        for _ in range(n_samples):
            template_entry = rng.choice(_TEMPLATES)
            text_template, complexity, domain, quality, privacy = template_entry

            # Fill in template slots
            text = self._fill_slots(text_template, rng)

            examples.append(
                TrainingExample(
                    text=text,
                    complexity_label=complexity,
                    domain_label=domain,
                    quality_label=quality,
                    privacy_label=privacy,
                )
            )

        logger.debug("Generated %d synthetic training examples (seed=%d).", n_samples, seed)
        return examples

    # ------------------------------------------------------------------
    # Internal helpers
    # ------------------------------------------------------------------

    @staticmethod
    def _fill_slots(template: str, rng: random.Random) -> str:
        """Replace slot markers in a template with random values."""
        result = template
        if "{LANG}" in result:
            result = result.replace("{LANG}", rng.choice(_LANG_CHOICES))
        if "{SUBJECT}" in result:
            result = result.replace("{SUBJECT}", rng.choice(_SUBJECT_CHOICES))
        if "{FORMAT}" in result:
            result = result.replace("{FORMAT}", rng.choice(_FORMAT_CHOICES))
        if "{LEVEL}" in result:
            result = result.replace("{LEVEL}", rng.choice(_LEVEL_CHOICES))
        return result
