from __future__ import annotations

import argparse
import hashlib
import json
import os
import pathlib
import sys


ROOT = pathlib.Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))

from reliability_core.harness import valid_documents
from reliability_core.runtime import WorkflowRuntime
from reliability_core.storage import Store


def file_hash(path: pathlib.Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("stage", choices=["stage1", "stage2"])
    parser.add_argument("database", type=pathlib.Path)
    parser.add_argument("run_id")
    parser.add_argument("case_id")
    args = parser.parse_args()
    store = Store(str(args.database))
    runtime = WorkflowRuntime(store=store, run_id=args.run_id)
    try:
        if args.stage == "stage1":
            result = runtime.execute(args.case_id, valid_documents())
        else:
            result = runtime.continue_ready(args.case_id, valid_documents())
    finally:
        store.close()
    output = {"stage": args.stage, "pid": os.getpid(), "database_ref": f"{args.database.parent.name}/{args.database.name}", "database_sha256": file_hash(args.database), "result": result}
    print(json.dumps(output, sort_keys=True))
    return 0


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