# SPDX-FileCopyrightText: 2026 Teilo Millet
# SPDX-License-Identifier: Apache-2.0

"""Optimize early-mode runner."""

from __future__ import annotations

import time
from typing import TYPE_CHECKING
from typing import cast as _cast

from vauban._pipeline._context import EarlyModeContext, log
from vauban._pipeline._mode_common import ModeReport, finish_mode_run, write_mode_report
from vauban._serializers import _optimize_to_dict

if TYPE_CHECKING:
    from vauban.types import CausalLM, Tokenizer


def _run_optimize_mode(context: EarlyModeContext) -> None:
    """Run [optimize] early-return mode and write its report."""
    config = context.config
    if config.optimize is None:
        msg = "optimize config is required for optimize mode"
        raise ValueError(msg)
    if context.direction_result is None:
        msg = "direction_result is required for optimize mode but was not computed"
        raise ValueError(msg)
    if context.harmful is None:
        msg = "harmful prompts are required for optimize mode but were not loaded"
        raise ValueError(msg)
    v = config.verbose
    model = _cast("CausalLM", context.model)
    tokenizer = _cast("Tokenizer", context.tokenizer)

    from vauban.measure import load_prompts
    from vauban.optimize import optimize

    log(
        f"Running optimization ({config.optimize.n_trials} trials)",
        verbose=v,
        elapsed=time.monotonic() - context.t0,
    )
    if config.eval.prompts_path is not None:
        eval_prompts = load_prompts(config.eval.prompts_path)
    else:
        eval_prompts = context.harmful[:config.eval.num_prompts]

    opt_result = optimize(
        model,
        tokenizer,
        context.direction_result,
        eval_prompts,
        config.optimize,
    )
    report_path = write_mode_report(
        config.output_dir,
        ModeReport("optimize_report.json", _optimize_to_dict(opt_result)),
    )
    log(
        f"Done — optimize report written to {report_path}",
        verbose=v,
        elapsed=time.monotonic() - context.t0,
    )
    finish_mode_run(
        context,
        "optimize",
        ["optimize_report.json"],
        {"n_trials": float(config.optimize.n_trials)},
    )
