from __future__ import annotations

import json
import os
import sys
import traceback
from pathlib import Path

os.environ.setdefault("PYTHONUTF8", "1")
os.environ.setdefault("PYTHONIOENCODING", "utf-8:replace")
os.environ["TQDM_DISABLE"] = "0"

try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass

ROOT = Path(__file__).resolve().parent
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from trainer import TrainOptions, run_training


def main() -> int:
    if len(sys.argv) < 2:
        print("job file is missing", flush=True)
        return 2

    job_path = Path(sys.argv[1])
    result_path = job_path.with_suffix(".result.json")
    try:
        payload = json.loads(job_path.read_text(encoding="utf-8"))
        result_path = Path(payload.get("result_path", str(result_path)))
        options = TrainOptions(**payload["options"])
        message, output_file = run_training(payload["target_image"], payload.get("pair_image"), options)
        result = {
            "ok": bool(output_file),
            "message": message,
            "output_file": output_file,
        }
    except Exception:
        result = {
            "ok": False,
            "message": "エラーが発生しました。\n\n" + traceback.format_exc(),
            "output_file": None,
        }

    result_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
    return 0 if result["ok"] else 1


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