#!/usr/bin/env python3
"""Guarded plan/execute/verify entry point for the term-26 source backfill."""

from __future__ import annotations

import json
import os
import sys
from pathlib import Path


def _emit(value: dict) -> None:
    print(json.dumps(value, sort_keys=True, separators=(",", ":"), default=str))


def main(argv: list[str] | None = None) -> int:
    argv = list(argv or sys.argv[1:])
    if len(argv) != 1 or argv[0] not in {"plan", "execute", "verify"}:
        _emit({"term_projection_backfill": "blocked", "reason": "unsupported action"})
        return 2

    app_dir = Path(os.environ.get("TT_PHASE1_APP_DIR", ".")).resolve()
    if str(app_dir) not in sys.path:
        sys.path.insert(0, str(app_dir))
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")

    import django

    django.setup()
    from api.services.integration.term_projection_backfill import (
        ENTRY_SOURCE_WATERMARK,
        TermProjectionBackfillError,
        build_plan,
        execute_backfill,
        wait_for_published_backfill,
    )

    action = argv[0]
    deployed_sha = os.environ.get("TT_PHASE1_TERM_DEPLOYED_SHA", "")
    expected_watermark = os.environ.get("TT_PHASE1_TERM_EXPECTED_WATERMARK", "")
    plan_sha256 = os.environ.get("TT_PHASE1_TERM_BACKFILL_PLAN_SHA256", "")
    mutation_confirmed = os.environ.get("TT_PHASE1_TERM_CONFIRM_OUTBOX_MUTATION") == "True"
    operational_confirmed = os.environ.get("TT_PHASE1_TERM_CONFIRM_OPERATIONAL") == "True"
    try:
        if expected_watermark != str(ENTRY_SOURCE_WATERMARK):
            raise TermProjectionBackfillError("approved entry source watermark is not exact")
        if operational_confirmed:
            raise TermProjectionBackfillError("operational confirmation must remain false")
        if action in {"plan", "verify"} and mutation_confirmed:
            raise TermProjectionBackfillError("read-only action received mutation confirmation")
        if action == "execute" and not mutation_confirmed:
            raise TermProjectionBackfillError("execute requires explicit outbox mutation confirmation")

        if action == "plan":
            result = build_plan(deployed_git_sha=deployed_sha)
            result["action"] = action
            result["term_projection_backfill"] = "planned"
        elif action == "execute":
            committed = execute_backfill(
                deployed_git_sha=deployed_sha,
                expected_plan_sha256=plan_sha256,
            )
            published = wait_for_published_backfill(
                expected_plan_sha256=plan_sha256,
            )
            result = {
                "action": action,
                "term_projection_backfill": "committed_and_published",
                "committed": committed,
                "published": published,
                "mutation_scope": "integration_outbox_only",
            }
        else:
            result = wait_for_published_backfill(
                expected_plan_sha256=plan_sha256,
                timeout_seconds=1,
                poll_seconds=0.1,
            )
            result["action"] = action
            result["term_projection_backfill"] = "verified"
        _emit(result)
        return 0
    except Exception as error:
        _emit(
            {
                "term_projection_backfill": "blocked",
                "action": action,
                "reason": str(error),
                "domain_mutation_executed": False,
                "outbox_mutation_may_have_committed": action == "execute",
                "engine_called": False,
                "resource_booking_accessed": False,
                "reverse_delivery_enabled": False,
                "phase2_enabled": False,
                "dr_executed": False,
            }
        )
        return 2


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