"""Write stand-in answers for a batch file, so that the later steps run without a model.

Purpose: read the batch file that `detect_and_shortlist.py` wrote and the
detections table, and write an output file in the format of the OpenAI batch
service with one fixed answer per request. Each answer names the most flagged
year in the request and classifies it as `insufficient_data`. The answers are
not model output. They let the parsing and review export steps run on a
machine without a provider key, and they are what a careful model would also
conclude about a fictional series.

Usage:
    python stand_in_answers.py run1/batch.jsonl run1/detections.csv --output run1/batch_output.jsonl

Requires pandas. Exit status: 0 when the file was written; 1 when an input
cannot be read or a request holds no year of the table.

What this does not check: that the answers describe the data in any real
sense. A real run replaces this file with the provider's output file.
"""

import argparse
import json
import sys
from pathlib import Path

import pandas as pd

ANSWER = {
    "is_anomaly": False,
    "classification": "insufficient_data",
    "confidence": 0.3,
    "explanation": (
        "Stand-in answer written without a model. The series is fictional, "
        "so no documented event can explain the value."
    ),
    "evidence_strength": "no_evidence",
    "evidence_source": [],
    "source": "llm_inferred",
}


def request_context(row: dict) -> dict:
    """Return the JSON context that a request carries in its user message.

    Parameters
    ----------
    row : dict
        One line of the batch file.

    Returns
    -------
    dict
        The context with the indicator, the country, and the series snippet.
    """
    text = row["body"]["input"][1]["content"][0]["text"]
    return json.loads(text.split("# CONTEXT", 1)[1].strip())


def main(argv: list[str] | None = None) -> int:
    """Write the stand-in output file.

    Parameters
    ----------
    argv : list[str] | None, optional
        Command arguments, or the process arguments when omitted.

    Returns
    -------
    int
        Zero when the file was written.
    """
    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    parser.add_argument("batch", type=Path)
    parser.add_argument("detections", type=Path)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args(argv)
    try:
        rows = [json.loads(line) for line in args.batch.read_text().splitlines()]
        ids = json.loads(
            args.batch.with_name(args.batch.stem + "_custom_id_map.json").read_text()
        )
        table = pd.read_csv(args.detections)
    except (OSError, ValueError) as error:
        print(f"Cannot read the input: {error}", file=sys.stderr)
        return 1

    lines = []
    for row in rows:
        key = ids[row["custom_id"]]
        years = {item["YEAR"] for item in request_context(row)["Series"]}
        series = table[
            (table["indicator_id"] == key["indicator_id"])
            & (table["geography_id"] == key["geography_id"])
            & table["period"].isin(years)
            & ~table["is_imputed"]
        ]
        if series.empty:
            print(f"No observation for request {row['custom_id']}", file=sys.stderr)
            return 1
        top = series.sort_values(["outlier_count", "anomaly_score"]).iloc[-1]
        answer = {"anomalies": [{"window": [int(top["period"])] * 2, **ANSWER}]}
        body = {"output": [{"content": [{"text": json.dumps(answer)}]}]}
        lines.append(
            json.dumps({"custom_id": row["custom_id"], "response": {"body": body}})
        )
    args.output.write_text("\n".join(lines) + "\n", encoding="utf-8")
    print(f"wrote {len(lines)} stand-in answers to {args.output}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
