# retoor <retoor@molodetz.nl>
from __future__ import annotations

import asyncio
import json
import logging
import sys
from pathlib import Path

from devplacepy.services.jobs.isslop.config import settings_from_payload
from devplacepy.services.jobs.isslop.events import KIND_ERROR, WorkerEvent
from devplacepy.services.jobs.isslop.pipeline import run_pipeline

logger = logging.getLogger(__name__)


def emit(event: WorkerEvent) -> None:
    print(event.to_json(), flush=True)


async def amain(payload_path: Path, workspace: Path) -> int:
    try:
        payload = json.loads(payload_path.read_text(encoding="utf-8"))
    except (OSError, ValueError) as error:
        emit(WorkerEvent(KIND_ERROR, f"Worker payload unreadable: {error}", {}))
        return 1
    settings = settings_from_payload(payload)
    source_url = str(payload.get("url", ""))
    failed = False
    try:
        async for event in run_pipeline(source_url, workspace, settings):
            emit(event)
            if event.kind == KIND_ERROR:
                failed = True
    except (OSError, ValueError, RuntimeError) as error:
        logger.exception("Pipeline crashed")
        emit(WorkerEvent(KIND_ERROR, f"Pipeline crashed: {error}", {}))
        return 1
    return 1 if failed else 0


def main() -> None:
    logging.basicConfig(level=logging.INFO, stream=sys.stderr)
    if len(sys.argv) != 3:
        emit(WorkerEvent(KIND_ERROR, "usage: worker <payload_json_path> <workspace_dir>", {}))
        sys.exit(2)
    exit_code = asyncio.run(amain(Path(sys.argv[1]), Path(sys.argv[2])))
    sys.exit(exit_code)


if __name__ == "__main__":
    main()
