"""Usage::

# Set the job ID you want to re-run, then:
python export_params_rerun.py

"""

import json

from orionclient.types import WorkFloeJob
from orionclient.session import APISession

session = APISession

# Replace with the ID of a completed job you want to re-run
SOURCE_JOB_ID = 12345
OUTPUT_FILE = f"job_{SOURCE_JOB_ID}_params.json"

# 1. Fetch the original job
print(f"Fetching job {SOURCE_JOB_ID}...")
original_job = session.get_resource(WorkFloeJob, SOURCE_JOB_ID)
print(f"  Name:     {original_job.name}")
print(f"  State:    {original_job.state}")
print(f"  Workfloe: {original_job.workfloe}")

# 2. Export its parameters
params = original_job.export_params()
print("\nExported parameters:")
print(json.dumps(params, indent=2))

# 3. Optionally write parameters to file
if OUTPUT_FILE:
    with open(OUTPUT_FILE, "w") as f:
        json.dump(params, f, indent=2)
    print(f"\nParameters written to {OUTPUT_FILE}")

# 4. Start a new job directly from the exported parameters.
# The WorkFloeSpec id stored in the dict is resolved automatically; here we
# override only the job name.
new_name = f"{params['name']} (re-run of job {SOURCE_JOB_ID})"
print(f"Starting new job: '{new_name}'...")

new_job = WorkFloeJob.start(
    session,
    param_dict=params,
    name=new_name,
)
print(f"  New job ID: {new_job.id}")
print(f"  State:      {new_job.state}")
