"""공식 MCP Python SDK 1.x로 손나루에 연결하는 공개 예제.

기본 실행은 발주 없이 도구와 계약 문맥을 읽습니다. 토큰은 환경변수
SONNARU_API_KEY 또는 숨김 입력으로만 받으며 인수·파일로 저장하지 않습니다.
발주와 예산 예약은 고객 본인이 손나루 웹에서만 합니다. --post는 견적을 받은 뒤 발주를 요청하지만
AI 키로는 서버가 human_confirmation_required로 거부하고 고객 웹 주소를 알려 줍니다(2026-11-15).
새 의뢰는 사용자가 무료 초안에 동의한 뒤 --job-draft로 시작합니다.
사람의 제출이나 관리자 검수를 대신 실행하지 않습니다.
"""

from __future__ import annotations

import argparse
from datetime import timedelta
import asyncio
import getpass
import hashlib
import json
import logging
import os
from pathlib import Path
import re
import secrets
import sys
import tempfile
import time
from contextlib import asynccontextmanager
from typing import Any
from urllib.parse import urlsplit

import httpx
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client

# 서버의 도구 목록(tools/list)에 반드시 보여야 하는 도구.
TOOLS = frozenset({
    "get_order_context", "get_workflow_progress", "get_result", "report_result_issue", "cancel_task",
    "upload_work_material", "get_work_materials",
})
# 호환용 도구: 2026-11-14(D210)부터 도구 목록에 보이지 않는다. 이름으로 호출하면 예전과 똑같이 동작하므로
# 이 예제의 기존 명령(--post, --match-action, 체크포인트 흐름)은 그대로 쓸 수 있다. 목록에 없다고 오류로 보지 않는다.
COMPAT_TOOLS = frozenset({
    "discover_workers", "find_capacity", "post_task", "get_status", "prepare_match_brief",
    "get_match_brief", "revise_match_brief", "assess_task_fit", "plan_human_help", "request_human_help",
    "get_pay_guidance",
})
# Earlier servers remain diagnosable. New request commands require their own tools;
# discovery is permission-dependent, and customer-web-only tools are never required.
JOB_REQUEST_TOOLS = frozenset({"draft_job_request", "submit_job_request"})
# 소개 조회는 권한이 있을 때만 목록에 보인다. 이전 서버는 호환용 도구도 목록에 보여 주므로 함께 선택 도구로 둔다.
OPTIONAL_TOOLS = JOB_REQUEST_TOOLS | COMPAT_TOOLS | frozenset({"search_capability_introductions"})
JOB_DRAFT_MAX_BYTES = 4096


def load_job_draft(path: str) -> dict[str, Any]:
    """개방형 의뢰서 초안 입력(요약 필드만)을 읽는다. 원문 자료·개인정보를 넣지 않는다."""
    file = Path(path)
    if not file.is_file() or file.stat().st_size > JOB_DRAFT_MAX_BYTES * 2:
        raise ConnectorError("초안 입력 파일을 찾을 수 없거나 너무 큽니다(요약 필드만, 4KB 이하).")
    try:
        value = json.loads(file.read_text(encoding="utf-8"))
    except (OSError, UnicodeError, json.JSONDecodeError):
        raise ConnectorError("초안 입력 파일은 UTF-8 JSON 객체여야 합니다.") from None
    if not isinstance(value, dict):
        raise ConnectorError("초안 입력 파일은 JSON 객체여야 합니다.")
    return value


def blocked_message(draft: dict[str, Any]) -> str:
    """제출할 수 없는 초안의 사람용 안내. 코드값 대신 서버가 준 한국어 이름표와 user_message만 쓴다."""
    message = draft.get("user_message") or "제출하기 전에 정해야 할 것이 있어요."
    # 서버가 준 질문이 있으면 그 질문을 그대로 붙인다(user_message의 '아래 질문'이 실제로 보이게).
    questions = [q["question"] for q in draft.get("missing_info_questions") or draft.get("questions") or []
                 if isinstance(q, dict) and q.get("blocking") and isinstance(q.get("question"), str)]
    if questions:
        return message + " 확인할 질문: " + " / ".join(questions)
    if draft.get("reason_label") or draft.get("status") in {"blocked", "human_not_needed"}:
        # 받을 수 없는 요청은 user_message가 이미 이유를 말한다. 같은 말을 '정할 것'으로 되풀이하지 않는다.
        return message
    labels = [label for label in draft.get("blocking_labels") or [] if isinstance(label, str)]
    return message + (f" 확인이 필요한 항목: {', '.join(labels)}." if labels else "")


async def job_request(session, args) -> dict[str, Any]:
    """draft_job_request(무료·무저장) → 명시한 경우에만 submit_job_request(고객 웹 확인 대기까지)."""
    names = {tool.name for tool in (await session.list_tools()).tools}
    if not JOB_REQUEST_TOOLS <= names:
        raise ConnectorError("이 서버에는 개방형 의뢰서 도구가 없습니다. 최신 손나루 연결 안내를 확인하세요.")
    draft = payload(await session.call_tool("draft_job_request", load_job_draft(args.job_draft)))
    output: dict[str, Any] = {"연결": "성공", "의뢰서_초안": {k: v for k, v in draft.items() if k != "draft_token"}, "업무_생성": False}
    if not args.job_submit:
        output["안내"] = "초안은 저장·연락·예산 예약이 없습니다. 사용자가 제출을 원하면 같은 파일로 --job-submit --request-id를 지정하세요."
        return output
    if not draft.get("submit_allowed") or not draft.get("draft_token"):
        raise ConnectorError(blocked_message(draft), draft.get("reason_code") or "job_draft_incomplete")
    submitted = payload(await session.call_tool("submit_job_request", {
        "draft_token": draft["draft_token"], "client_request_id": args.request_id, "confirmed": True}))
    output["의뢰서_제출"] = submitted
    output["안내"] = "confirmed=true는 사람 확인이 아닙니다. confirmation_url에서 고객 본인이 직접 확인해야 사람 찾기가 시작됩니다."
    return output
TERMINAL = frozenset({"completed", "cancelled", "rejected"})


class ConnectorError(Exception):
    """요청 헤더나 서버 예외를 포함하지 않는 사용자 안내."""

    def __init__(self, message: str, code: str = "connector_error"):
        self.code = code
        super().__init__(message)


def validate_endpoint(value: str) -> str:
    try:
        parsed = urlsplit(value.strip())
        hostname = parsed.hostname
        _ = parsed.port
    except (AttributeError, ValueError):
        raise ConnectorError("올바른 MCP 주소를 지정하세요.") from None
    if not hostname or parsed.username is not None or parsed.password is not None or parsed.query or parsed.fragment or parsed.path not in {"", "/", "/mcp", "/mcp/"}:
        raise ConnectorError("인증정보·쿼리 없이 손나루 MCP 주소를 지정하세요.")
    if parsed.scheme != "https" and not (parsed.scheme == "http" and hostname.lower() in {"localhost", "127.0.0.1", "::1"}):
        raise ConnectorError("외부 MCP 서버에는 HTTPS를 사용하세요.")
    return f"{parsed.scheme}://{parsed.netloc}/mcp/"


def load_token() -> str:
    token = os.environ.get("SONNARU_API_KEY", "")
    if not token and sys.stdin.isatty():
        token = getpass.getpass("손나루 AI 키 (화면에 표시되지 않음): ")
    token = token.strip()
    if not 12 <= len(token) <= 256 or not all(c.isascii() and (c.isalnum() or c in "._~-") for c in token):
        raise ConnectorError("SONNARU_API_KEY 환경변수 또는 숨김 입력에 유효한 고객 AI 키를 지정하세요.")
    return token


def redact(value: Any, token: str) -> Any:
    if isinstance(value, str):
        return value.replace(token, "[비공개]") if token else value
    if isinstance(value, list):
        return [redact(item, token) for item in value]
    if isinstance(value, dict):
        return {key: redact(item, token) for key, item in value.items()}
    return value


def payload(result) -> dict[str, Any]:
    value = result.structuredContent
    if value is None:
        try:
            value = json.loads(next(item.text for item in result.content if item.type == "text"))
        except (ValueError, StopIteration):
            raise ConnectorError("MCP 응답 형식을 확인하지 못했습니다.", "invalid_mcp_result") from None
    if not isinstance(value, dict):
        raise ConnectorError("MCP 응답 형식을 확인하지 못했습니다.", "invalid_mcp_result")
    if result.isError:
        code = (value.get("error") or {}).get("code", "mcp_error")
        if not isinstance(code, str) or not re.fullmatch(r"[a-z_]{1,80}", code):
            code = "mcp_error"
        if code == "human_confirmation_required":
            # 발주·예산 예약(post), 조건서 합의·질문·진행 요청은 고객 본인 웹 단계다(맡길 사람의 확정과 위탁 제안은 손나루). AI 키로는 서버가 항상 거부한다.
            url = (value.get("error") or {}).get("customer_web_url")
            where = url if isinstance(url, str) and re.fullmatch(r"https?://[A-Za-z0-9.:\[\]-]+(/[A-Za-z0-9._~/-]*)?(\?[A-Za-z0-9_=&-]{0,80})?", url) else "손나루 웹"
            raise ConnectorError("이 단계(발주·예산 예약, 합의·질문·진행 요청)는 고객 본인이 " + where + "에서 직접 해야 해요. "
                                 "웹에서 마친 뒤 --workflow-action resume 또는 --task-id로 이어서 조회하세요. 오류 코드: " + code, code)
        raise ConnectorError("MCP 도구가 요청을 거절했습니다. 허용 장소·계약 예산·작업 상태를 확인하세요. 오류 코드: " + code, code)
    return value


def load_task_spec(filename: str | None) -> dict[str, Any] | None:
    """The public download stays standalone; server-side validation remains authoritative."""
    if not filename:
        return None
    try:
        path = Path(filename)
        if path.stat().st_size > 32768:
            raise ValueError
        value = json.loads(path.read_text(encoding="utf-8-sig"), parse_constant=lambda _: (_ for _ in ()).throw(ValueError()))
        if not isinstance(value, dict) or value.get("version") != 1:
            raise ValueError
    except (OSError, ValueError, TypeError):
        raise ConnectorError("작업 사양은 version=1인 32KB 이내 JSON 객체 파일로 지정하세요.") from None
    return value


def task_arguments(args, *, workflow: bool = False) -> dict[str, Any]:
    kind = args.task_type or ("human_task" if workflow or args.project_id else "notice_display_check")
    spec = load_task_spec(args.task_spec)
    if kind == "human_task" and spec is None and (args.match_action == "prepare" or workflow):
        raise ConnectorError("범용 협의 작성에는 --task-spec JSON 파일이 필요합니다.")
    if kind != "human_task" and spec is not None:
        raise ConnectorError("--task-spec은 --task-type human_task와 함께 사용하세요.")
    return {"task_type": kind, **({"task_spec": spec} if spec is not None else {})}


def work_scope_arguments(args, *, required: bool = False) -> dict[str, Any]:
    pid, sid, mode = args.project_id, args.site_id, args.work_mode
    if pid is None and sid is None and mode is None:
        if required:
            raise ConnectorError("프로젝트·참여 방식 또는 기존 방문 장소를 지정하세요.")
        return {}
    if any(value is not None and (not isinstance(value,str) or not 1<=len(value)<=80) for value in (pid,sid)):
        raise ConnectorError("프로젝트·장소 번호를 확인하세요.")
    if pid is not None and mode is None:
        raise ConnectorError("프로젝트 업무에는 --work-mode remote, on_site, hybrid를 명시하세요.")
    mode = mode or "on_site"
    if mode == "remote":
        if not pid or sid is not None:
            raise ConnectorError("원격 업무에는 --project-id를 지정하고 --site-id는 넣지 마세요.")
    elif not sid or (mode == "hybrid" and not pid):
        raise ConnectorError("방문·혼합 업무에는 --site-id가 필요하며 혼합에는 프로젝트도 필요합니다.")
    if pid is None and args.work_mode is None:
        return {"site_id":sid}  # Preserve the legacy payload and retry hash.
    return {"project_id":pid,"work_mode":mode,"site_id":sid}


def _same_work_scope(expected, actual):
    return all(actual.get(key, "on_site" if key=="work_mode" else None)==expected.get(key,"on_site" if key=="work_mode" else None)
               for key in ("project_id","work_mode","site_id"))


def _check_context_scope(context, selected, order_id=None):
    if selected.get("project_id") and not any(p.get("id")==selected["project_id"] for p in context.get("projects",[])):
        raise ConnectorError("현재 연결에 허용된 프로젝트가 아닙니다. 고객 화면의 AI 키 범위를 확인하세요.","checkpoint_scope_mismatch")
    if selected.get("site_id") and "sites" in context and not any(s.get("id")==selected["site_id"] for s in context["sites"]):
        raise ConnectorError("현재 연결에 허용된 방문 장소가 아닙니다.","checkpoint_scope_mismatch")
    if order_id and selected.get("project_id"):
        order=next((row for row in context.get("orders",[]) if row.get("id")==order_id),None)
        if not order or ("project_id" in order and not _same_work_scope(selected,order)):
            raise ConnectorError("계약 발주번호가 선택한 프로젝트·참여 방식과 다릅니다.","checkpoint_scope_mismatch")


@asynccontextmanager
async def connected(endpoint: str, token: str):
    try:
        async with (
            httpx.AsyncClient(headers={"Authorization": f"Bearer {token}"}, timeout=httpx.Timeout(30, read=110), follow_redirects=False) as http_client,
            streamable_http_client(endpoint, http_client=http_client) as (read, write, _),
            ClientSession(read, write, read_timeout_seconds=timedelta(seconds=120)) as session,
        ):
            await session.initialize()
            yield session
    except BaseException as exc:
        # SDK task groups wrap a safe domain error; preserve its actionable retry code.
        def find(error):
            if isinstance(error, ConnectorError):
                return error
            for child in getattr(error, "exceptions", ()):
                found = find(child)
                if found:
                    return found
            return None
        safe = find(exc)
        if safe:
            raise safe from None
        raise


def match_arguments(args) -> tuple[str, dict[str, Any]]:
    """Convert explicit matching actions to scoped MCP arguments; no default contact."""
    action = args.match_action
    if args.post:
        raise ConnectorError("업무 발주와 매칭 협의는 따로 실행하세요.")
    if action == "prepare":
        scope=work_scope_arguments(args,required=True)
        if not all((args.purpose, args.deadline_at, args.request_id)) or not args.max_total or args.max_total <= 0:
            raise ConnectorError("협의안 작성에는 업무 범위·--purpose·--deadline-at·--request-id·양수 --max-total이 필요합니다.")
        return "prepare_match_brief", {
            **scope, "purpose": args.purpose, "deadline_at": args.deadline_at,
            "budget_total": args.max_total, "client_request_id": args.request_id,
            **task_arguments(args),
        }
    if not args.brief_id:
        raise ConnectorError("매칭 협의 조회·수정에는 --brief-id가 필요합니다.")
    base: dict[str, Any] = {"brief_id": args.brief_id}
    if action == "inspect":
        return "get_match_brief", base
    if action == "evidence":
        if not args.candidate_ref:
            raise ConnectorError("후보 근거 조회에는 --candidate-ref가 필요합니다.")
        return "get_fit_evidence", base | {"candidate_ref": args.candidate_ref}
    if not args.request_id or args.brief_version is None or args.brief_version < 1:
        raise ConnectorError("조건 합의·질문·제안에는 --request-id와 양수 --brief-version이 필요합니다.")
    base |= {"expected_version": args.brief_version, "client_request_id": args.request_id}
    if action == "agree":
        return "revise_match_brief", base | {"accept": True}
    if action == "ask":
        if args.candidate_ref:
            base["candidate_ref"] = args.candidate_ref
        return "request_fit_questions", base
    if action == "propose":
        if not args.candidate_ref or not args.task_id:
            raise ConnectorError("진행 요청에는 --candidate-ref와 기존 --task-id가 필요합니다.")
        return "propose_candidate", base | {"candidate_ref": args.candidate_ref, "task_id": args.task_id}
    raise ConnectorError("지원하는 매칭 동작을 선택하세요.")


WORKFLOW_ACTIONS = ("prepare", "agree", "ask", "refresh", "quote", "requote", "post", "propose", "resume")
CHECKPOINT_FIELDS = frozenset({
    "version", "endpoint", "namespace", "client_scope", "workflow_id", "brief_id", "task_id",
    "site_id", "project_id", "work_mode", "deadline_at", "task_type", "quote_id", "order_id", "max_total", "fit_request_id",
    "brief_version", "status", "stage", "commands", "quote_state", "quote_generation", "previous_quotes",
})


def _valid_command(command):
    return (isinstance(command, dict)
            and {"request_id", "payload_hash", "expected_version", "status"} <= set(command)
            and not set(command) - {"request_id", "payload_hash", "expected_version", "status", "error_code"}
            and command["status"] in {"pending", "completed", "rejected"}
            and isinstance(command["request_id"], str)
            and re.fullmatch(r"[A-Za-z0-9_.:-]{8,120}", command["request_id"])
            and isinstance(command["payload_hash"], str)
            and re.fullmatch(r"[a-f0-9]{64}", command["payload_hash"])
            and (command["expected_version"] is None or type(command["expected_version"]) is int)
            and ("error_code" not in command or isinstance(command["error_code"], str) and re.fullmatch(r"[a-z_]{1,80}", command["error_code"])))


def _hash(value: Any) -> str:
    return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode()).hexdigest()


def save_checkpoint(path: Path, state: dict[str, Any]) -> None:
    """Allowlisted metadata only, atomically replaced; results and credentials never enter it."""
    if path.is_symlink() or set(state) - CHECKPOINT_FIELDS:
        raise ConnectorError("체크포인트 파일 형식을 확인하세요.")
    data = json.dumps(state, ensure_ascii=False, indent=2, allow_nan=False)
    if len(data.encode()) > 65536:
        raise ConnectorError("체크포인트 파일 형식을 확인하세요.")
    tmp_name = None
    try:
        with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, prefix=".sonnaru-", delete=False) as stream:
            tmp_name = stream.name
            os.chmod(tmp_name, 0o600)
            stream.write(data)
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(tmp_name, path)
        tmp_name = None
    except OSError:
        raise ConnectorError("체크포인트를 안전하게 저장하지 못했습니다. 쓰기 권한과 디스크를 확인하세요.") from None
    finally:
        if tmp_name:
            try:
                os.unlink(tmp_name)
            except OSError:
                pass


def load_checkpoint(path: Path, endpoint: str, namespace: str, scope: str) -> dict[str, Any]:
    try:
        if path.is_symlink() or path.stat().st_size > 65536:
            raise ValueError
        state = json.loads(path.read_text(encoding="utf-8"))
        if (not isinstance(state, dict) or set(state) - CHECKPOINT_FIELDS or state.get("version") != 1
                or not {"endpoint", "namespace", "client_scope", "workflow_id", "commands"} <= set(state)
                or not isinstance(state.get("commands"), dict)
                or not re.fullmatch(r"[a-f0-9]{24}", state.get("workflow_id", ""))):
            raise ValueError
        for action, command in state["commands"].items():
            if action not in WORKFLOW_ACTIONS or not _valid_command(command):
                raise ValueError
        if type(state.get("quote_generation", 0)) is not int or not 0 <= state.get("quote_generation", 0) <= 10:
            raise ValueError
        if state.get("project_id") is not None:
            if (not isinstance(state["project_id"],str) or not 1<=len(state["project_id"])<=80
                    or state.get("work_mode") not in {"remote","on_site","hybrid"}):
                raise ValueError
        if "work_mode" in state and state["work_mode"] not in {"remote","on_site","hybrid"}:
            raise ValueError
        if state.get("site_id") is not None and (not isinstance(state["site_id"],str) or not 1<=len(state["site_id"])<=80):
            raise ValueError
        if state.get("work_mode")=="remote" and (not state.get("project_id") or state.get("site_id") is not None):
            raise ValueError
        if state.get("work_mode")=="hybrid" and (not state.get("project_id") or not state.get("site_id")):
            raise ValueError
        history = state.get("previous_quotes", [])
        if not isinstance(history, list) or len(history) > 10:
            raise ValueError
        for quote in history:
            if (not isinstance(quote, dict) or set(quote) != {"quote_id", "order_id", "quote_generation", "post_command"}
                    or not isinstance(quote["quote_id"], str) or not isinstance(quote["order_id"], str)
                    or type(quote["quote_generation"]) is not int or not _valid_command(quote["post_command"])):
                raise ValueError
    except (OSError, ValueError, TypeError):
        raise ConnectorError("체크포인트를 읽지 못했습니다. 원본 파일을 보존하고 형식을 확인하세요.") from None
    if state["endpoint"] != endpoint or state["namespace"] != namespace or state["client_scope"] != scope:
        raise ConnectorError("이 체크포인트의 서버·고객·이름공간이 현재 연결과 다릅니다.", "checkpoint_scope_mismatch")
    return state


async def _progress(session, state) -> dict[str, Any]:
    key = "task_id" if state.get("task_id") else "brief_id"
    if not state.get(key):
        raise ConnectorError("협의 번호를 아직 확인하지 못했습니다. 같은 prepare 입력으로 재시도하세요.")
    value = payload(await session.call_tool("get_workflow_progress", {key: state[key]}))
    if value.get("client_scope") != state["client_scope"]:
        raise ConnectorError("서버가 반환한 고객 범위를 확인하지 못했습니다.", "checkpoint_scope_mismatch")
    if value.get(key) != state[key] or value.get("schema_version") != 1:
        raise ConnectorError("현재 흐름과 일치하는 진행 응답이 아닙니다.", "invalid_workflow_progress")
    if state.get("project_id") and not _same_work_scope(state,value):
        raise ConnectorError("서버 진행의 프로젝트·참여 방식이 체크포인트와 다릅니다.","checkpoint_scope_mismatch")
    if state.get("brief_id") and value.get("brief_id") != state["brief_id"]:
        raise ConnectorError("현재 조건서와 연결된 진행 응답이 아닙니다.", "invalid_workflow_progress")
    if key == "brief_id" and value.get("task_id"):
        linked = value.get("task_ids")
        if not isinstance(linked, list) or len(linked) != 1 or linked[0] != value["task_id"]:
            raise ConnectorError("연결된 발주를 하나로 확정하지 못했습니다. 원래 post를 재시도해 작업 번호를 확정하세요.", "ambiguous_workflow_task")
        state["task_id"] = value["task_id"]
    if value.get("brief_version") is not None:
        state["brief_version"] = value["brief_version"]
    for name in ("status", "stage"):
        if isinstance(value.get(name), str):
            state[name] = value[name]
    return value


def _candidate(args, state, current):
    rid = args.fit_request_id or state.get("fit_request_id")
    if not rid:
        raise ConnectorError("맡기고 싶은 참여자는 --fit-request-id로 명시하세요. resume 응답의 candidates에서 번호를 확인할 수 있습니다.")
    if state.get("fit_request_id") and state["fit_request_id"] != rid and (state.get("quote_id") or state.get("task_id")):
        raise ConnectorError("견적 이후에는 체크포인트의 후보를 변경할 수 없습니다.")
    found = next((c for c in current.get("candidates", []) if c.get("fit_request_id") == rid), None)
    if not found:
        raise ConnectorError("현재 작업에서 이 후보를 조회할 수 없습니다. 동의·기한·권한을 확인하세요.")
    state["fit_request_id"] = rid
    return found


async def _mutate(session, path, state, action, tool, arguments, request_id=None):
    old = state["commands"].get(action)
    suffix = f"post-{state.get('quote_generation', 0)}" if action == "post" else action
    key = request_id or (old["request_id"] if old else f"sn-{state['workflow_id']}-{suffix}")
    if not re.fullmatch(r"[A-Za-z0-9_.:-]{8,120}", key):
        raise ConnectorError("중복 방지 ID는 영문·숫자·기호 8~120자로 지정하세요.")
    if old and old["request_id"] == key and old["status"] == "completed":
        raise ConnectorError("이미 처리한 단계입니다. resume으로 현재 상태를 확인하세요. 새 갱신은 새 --request-id를 명시하세요.")
    if action == "post" and old and old["request_id"] != key:
        raise ConnectorError("같은 발주는 원래 요청 ID·견적·금액으로만 재시도하세요.")
    if action == "post" and any(quote["post_command"]["request_id"] == key for quote in state.get("previous_quotes", [])):
        raise ConnectorError("새 견적에는 이전에 만료된 발주 시도의 요청 ID를 재사용할 수 없습니다.")
    if old and old["status"] == "pending" and old["request_id"] != key:
        raise ConnectorError("앞선 응답을 확인하기 전에는 새 요청 ID로 바꿀 수 없습니다. 원래 동작을 재시도하거나 서버 상태를 확인하세요.", "request_outcome_unknown")
    if old and old["request_id"] == key and old["status"] == "pending" and "expected_version" in arguments:
        arguments["expected_version"] = old["expected_version"]
    arguments = {**arguments, "client_request_id": key}
    signature = _hash(arguments)
    if old and old["request_id"] == key and old["payload_hash"] != signature:
        raise ConnectorError("응답을 기다리던 동작의 입력이 달라졌습니다. 원래 입력을 유지하세요.", "checkpoint_input_conflict")
    command = {"request_id": key, "payload_hash": signature, "expected_version": arguments.get("expected_version"), "status": "pending"}
    state["commands"][action] = command
    save_checkpoint(path, state)
    try:
        result = payload(await session.call_tool(tool, arguments))
    except ConnectorError as exc:
        if exc.code in {"invalid_mcp_result", "internal_error"}:
            raise ConnectorError("응답 수신을 확인하지 못했습니다. 체크포인트를 보존하고 같은 동작·입력으로 명시적으로 재시도하세요.", "request_outcome_unknown") from None
        command["status"] = "rejected"
        command["error_code"] = exc.code
        save_checkpoint(path, state)
        raise
    except Exception:
        raise ConnectorError("응답 수신을 확인하지 못했습니다. 체크포인트를 보존하고 같은 동작·입력으로 명시적으로 재시도하세요.", "request_outcome_unknown") from None
    command["status"] = "completed"
    # Save returned resource IDs in the same replacement as command completion.
    if action == "prepare":
        state["brief_id"] = result["id"]
    elif action == "post":
        state["task_id"] = result["id"]
    save_checkpoint(path, state)
    return result


async def workflow(session, args, endpoint: str) -> dict[str, Any]:
    """One explicit action per process. Resume only reads, never contacts or posts."""
    if type(args.wait_seconds) is not int or not 0 <= args.wait_seconds <= 3600:
        raise ConnectorError("대기 시간은 0~3600초로 지정하세요.")
    if not args.checkpoint or not args.client_namespace or not re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.client_namespace):
        raise ConnectorError("흐름 실행에는 --checkpoint와 영문·숫자 이름인 --client-namespace가 필요합니다.")
    path = Path(os.path.abspath(args.checkpoint))
    if path.is_symlink():
        raise ConnectorError("심볼릭 링크 대신 독립된 체크포인트 파일을 사용하세요.")
    if not path.parent.is_dir():
        raise ConnectorError("체크포인트를 저장할 폴더를 먼저 만드세요.")
    lock = path.with_name(path.name + ".lock")
    try:
        descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
    except OSError:
        raise ConnectorError("다른 실행이 이 체크포인트를 사용 중이거나 잠금 파일이 남아 있습니다. 실행 상태를 먼저 확인하세요.") from None
    os.close(descriptor)
    try:
        context = payload(await session.call_tool("get_order_context", {}))
        scope = context.get("client_scope")
        if not isinstance(scope, str) or not scope:
            raise ConnectorError("서버의 고객 범위 확인 기능이 필요합니다. 서버와 연결 예제를 함께 업데이트하세요.")
        if path.exists():
            state = load_checkpoint(path, endpoint, args.client_namespace, scope)
        else:
            if args.workflow_action != "prepare":
                raise ConnectorError("처음에는 prepare로 새 체크포인트와 협의를 만드세요.")
            state = {"version": 1, "endpoint": endpoint, "namespace": args.client_namespace, "client_scope": scope,
                     "workflow_id": secrets.token_hex(12), "commands": {}}
        selected=work_scope_arguments(args,required=args.workflow_action=="prepare")
        if ("project_id" in state or "site_id" in state) and selected and not _same_work_scope(state,selected):
            raise ConnectorError("다른 프로젝트·참여 방식·장소에는 새 체크포인트를 사용하세요.","checkpoint_scope_mismatch")
        effective=selected or {key:state.get(key) for key in ("project_id","work_mode","site_id")}
        if effective.get("project_id"):
            _check_context_scope(context,effective,args.order_id or state.get("order_id"))
        action = args.workflow_action
        output: dict[str, Any] = {"연결": "성공", "동작": action, "업무_생성": False, "자동_후속행동_실행": False}
        if action == "prepare":
            spec_args = task_arguments(args, workflow=True)
            purpose = args.purpose or (spec_args.get("task_spec") or {}).get("title")
            if not all((purpose, args.deadline_at)) or not args.max_total or args.max_total <= 0:
                raise ConnectorError("prepare에는 업무 범위·--deadline-at·양수 --max-total과 작업 목적이 필요합니다.")
            arguments = {**selected, "purpose": purpose, "deadline_at": args.deadline_at,
                         "budget_total": args.max_total, **spec_args}
            state.update({**selected, "deadline_at": args.deadline_at, "task_type": spec_args["task_type"], "max_total": args.max_total})
            await _mutate(session, path, state, action, "prepare_match_brief", arguments, args.request_id)
        elif action == "resume":
            end = time.monotonic() + args.wait_seconds
            while True:
                current = await _progress(session, state)
                save_checkpoint(path, state)
                output["진행"] = current
                if current.get("result_ready"):
                    result = payload(await session.call_tool("get_result", {"task_id": state["task_id"]}))
                    if result.get("task_id") != state["task_id"] or result.get("status") != "completed":
                        raise ConnectorError("현재 작업의 검수 완료 결과가 아닙니다.", "invalid_mcp_result")
                    output["검수_결과"] = result
                    output["후속_자동행동_허용"] = (result.get("quality") or {}).get("automation_allowed") is True and result.get("outcome") not in {"unable", "unknown"}
                    break
                if current.get("terminal") or time.monotonic() >= end:
                    break
                suggested = current.get("next_check_after_seconds")
                # A host must explicitly take the next action; do not poll an actionable gate.
                if suggested is None or not isinstance(suggested, (int, float)) or isinstance(suggested, bool):
                    break
                await asyncio.sleep(min(max(5, suggested), max(0, end - time.monotonic())))
            output["안내"] = "체크포인트를 보존하고 나중에 resume으로 이어가세요. 질문·발주·제안은 해당 동작을 명시해야 실행됩니다."
            return output
        else:
            current = await _progress(session, state)
            save_checkpoint(path, state)
            base = {"brief_id": state["brief_id"], "expected_version": current["brief_version"]}
            if action in {"agree", "ask"}:
                tool = "revise_match_brief" if action == "agree" else "request_fit_questions"
                await _mutate(session, path, state, action, tool, base | ({"accept": True} if action == "agree" else {}), args.request_id)
            elif action == "refresh":
                candidate = _candidate(args, state, current)
                await _mutate(session, path, state, action, "refresh_candidate_ref", base | {"fit_request_id": candidate["fit_request_id"]}, args.request_id)
            elif action in {"quote", "requote"}:
                if state.get("quote_state") == "pending":
                    raise ConnectorError("앞선 견적 응답을 확인하지 못했습니다. 운영자에게 조회를 요청한 뒤 새 흐름 여부를 결정하세요.", "quote_outcome_unknown")
                previous = None
                if action == "requote":
                    old_post = state["commands"].get("post")
                    if (not state.get("quote_id") or state.get("task_id") or current.get("task_ids") != []
                            or not old_post or old_post.get("status") != "rejected" or old_post.get("error_code") != "quote_expired"):
                        raise ConnectorError("requote는 기존 발주가 없고 서버가 quote_expired로 명확히 거절한 경우에만 가능합니다. 불명확한 발주는 원래 post로 확인하세요.")
                    if len(state.get("previous_quotes", [])) >= 10:
                        raise ConnectorError("재견적 횟수 상한에 도달했습니다. 운영자에게 기존 흐름 확인을 요청하세요.")
                    if args.order_id and args.order_id != state["order_id"]:
                        raise ConnectorError("재견적에서 원래 계약 발주번호를 변경할 수 없습니다.")
                    previous = {"quote_id": state["quote_id"], "order_id": state["order_id"],
                                "quote_generation": state.get("quote_generation", 0), "post_command": dict(old_post)}
                elif state.get("quote_id"):
                    raise ConnectorError("견적이 이미 저장돼 있습니다. 같은 견적으로 post를 실행하고 quote_expired이면 requote를 명시하세요.")
                if action == "quote" and not args.order_id:
                    raise ConnectorError("quote에는 --order-id가 필요합니다.")
                if args.quote_id:
                    # 후보를 지정한 견적은 수행자 선택이라 고객 본인이 sonnaru.com에서 만든다(서버가 AI 연결의 후보 지정 견적을 거부).
                    # 여기서는 고객이 알려 준 견적 번호만 체크포인트에 기록한다. 금액·소유·만료는 post에서 서버가 다시 검사한다.
                    if not re.fullmatch(r"[A-Za-z0-9_.:-]{3,120}", args.quote_id):
                        raise ConnectorError("견적 번호 형식을 확인하세요.")
                    if previous:
                        state.setdefault("previous_quotes", []).append(previous)
                        state["quote_generation"] = previous["quote_generation"] + 1
                        state["commands"].pop("post")
                    state.update({"quote_id": args.quote_id, "quote_state": "completed",
                                  "order_id": state.get("order_id") if previous else args.order_id})
                    save_checkpoint(path, state)
                    output["견적"] = {"quote_id": args.quote_id, "source": "customer_web"}
                    output["진행"] = await _progress(session, state)
                    save_checkpoint(path, state)
                    return output
                candidate = _candidate(args, state, current)
                if not candidate.get("candidate_ref") or candidate.get("ref_refresh_required"):
                    raise ConnectorError("후보 참조를 먼저 refresh로 갱신하세요.")
                state.update({"quote_state": "pending", "order_id": state.get("order_id") if previous else args.order_id})
                save_checkpoint(path, state)
                try:
                    quote = payload(await session.call_tool("find_capacity", {
                        **({key:state.get(key) for key in ("project_id","work_mode","site_id")} if state.get("project_id") else {"site_id":state["site_id"]}),
                        "task_type": state["task_type"], "order_id": state["order_id"],
                        "deadline_at": state["deadline_at"], "candidate_ref": candidate["candidate_ref"],
                    }))
                except ConnectorError as exc:
                    if exc.code in {"invalid_mcp_result", "internal_error"}:
                        raise ConnectorError("견적 응답을 확인하지 못했습니다. 운영자에게 기존 견적 확인을 요청하세요.", "quote_outcome_unknown") from None
                    state["quote_state"] = "rejected"
                    save_checkpoint(path, state)
                    raise
                except Exception:
                    raise ConnectorError("견적 응답을 확인하지 못했습니다. 새 견적을 자동 생성하지 않았습니다. 운영자에게 조회를 요청하세요.", "quote_outcome_unknown") from None
                if previous:
                    state.setdefault("previous_quotes", []).append(previous)
                    state["quote_generation"] = previous["quote_generation"] + 1
                    state["commands"].pop("post")
                state.update({"quote_id": quote["quote_id"], "quote_state": "completed"})
                save_checkpoint(path, state)
                if quote["price_total"] > state["max_total"]:
                    raise ConnectorError("견적이 체크포인트의 상한을 초과했습니다. 발주하지 않았습니다.")
                output["견적"] = quote
            elif action == "post":
                if state.get("quote_state") == "pending":
                    raise ConnectorError("견적 응답이 불명확하여 발주하지 않습니다. 운영자에게 기존 견적 확인을 요청하세요.", "quote_outcome_unknown")
                if not state.get("quote_id") or not state.get("order_id"):
                    raise ConnectorError("먼저 quote로 견적을 확인하고 저장하세요.")
                await _mutate(session, path, state, action, "post_task", {
                    "quote_id": state["quote_id"], "order_id": state["order_id"], "max_total": state["max_total"],
                }, args.request_id)
                output["업무_생성"] = True
            elif action == "propose":
                if not state.get("task_id"):
                    raise ConnectorError("먼저 post로 작업을 발주하세요.")
                previous = state["commands"].get("propose")
                if previous and previous["status"] == "pending" and current.get("proposal_id"):
                    previous["status"] = "completed"
                    save_checkpoint(path, state)
                    output["진행"] = current
                    output["안내"] = "서버에서 기존 제안을 확인했습니다. 새 제안을 보내지 않았습니다."
                    return output
                candidate = _candidate(args, state, current)
                if not candidate.get("candidate_ref") or candidate.get("ref_refresh_required"):
                    raise ConnectorError("후보 참조를 먼저 refresh로 갱신하세요.")
                await _mutate(session, path, state, action, "propose_candidate", base | {"task_id": state["task_id"], "candidate_ref": candidate["candidate_ref"]}, args.request_id)
        output["진행"] = await _progress(session, state)
        save_checkpoint(path, state)
        return output
    finally:
        try:
            lock.unlink()
        except OSError:
            pass


async def run(args, token: str) -> dict[str, Any]:
    endpoint = validate_endpoint(args.endpoint)
    if args.wait_seconds < 0 or args.wait_seconds > 3600:
        raise ConnectorError("대기 시간은 0~3600초로 지정하세요.")
    selected=work_scope_arguments(args,required=args.post)
    if args.post and (not args.order_id or not args.request_id or not args.max_total or args.max_total <= 0):
        raise ConnectorError("발주에는 업무 범위·--order-id·--request-id·양수 --max-total이 모두 필요합니다.")
    if args.post and args.task_id:
        raise ConnectorError("새 발주와 기존 업무 조회는 따로 실행하세요.")
    if args.quote_id and not args.post:
        if not args.workflow_action:
            raise ConnectorError("--quote-id는 동일한 발주를 재시도할 때 --post와 함께 사용하세요.")
    if args.quote_id and selected.get("project_id") and not args.workflow_action:
        raise ConnectorError("프로젝트 발주의 재시도는 범위가 저장된 --checkpoint 흐름의 post로 재개하세요.")
    if args.job_submit and not args.job_draft:
        raise ConnectorError("--job-submit은 --job-draft 초안 입력 파일과 함께 사용하세요.")
    if args.job_draft:
        if args.post or args.match_action or args.task_id or args.brief_id or args.workflow_action:
            raise ConnectorError("개방형 의뢰서 초안·제출은 다른 동작과 따로 실행하세요.")
        if args.job_submit and not args.request_id:
            raise ConnectorError("의뢰서 제출에는 재시도 때 유지할 --request-id가 필요합니다.")
        async with connected(endpoint, token) as session:
            return redact(await job_request(session, args), token)
    if args.workflow_action:
        if args.post or args.match_action or args.task_id or args.brief_id:
            raise ConnectorError("체크포인트 흐름과 기존 개별 동작은 따로 실행하세요.")
        async with connected(endpoint, token) as session:
            return redact(await workflow(session, args, endpoint), token)
    matching = match_arguments(args) if args.match_action else None
    async with connected(endpoint, token) as session:
        listed = await session.list_tools()
        names = {tool.name for tool in listed.tools}
        if not TOOLS <= names:
            raise ConnectorError("도구 목록이 예제와 다릅니다. 최신 손나루 연결 안내를 확인하세요.")
        output: dict[str, Any] = {"연결": "성공", "도구": sorted(names), "업무_생성": False}
        context=None
        if selected.get("project_id"):
            context=payload(await session.call_tool("get_order_context", {}))
            _check_context_scope(context,selected,args.order_id)
            output["선택한_업무_범위"]=selected
        if matching:
            tool_name, arguments = matching
            if selected.get("project_id") and args.match_action!="prepare":
                brief=payload(await session.call_tool("get_match_brief",{"brief_id":args.brief_id}))
                if not _same_work_scope(selected,brief):
                    raise ConnectorError("협의안의 프로젝트·참여 방식이 현재 입력과 다릅니다.","checkpoint_scope_mismatch")
            output["매칭_도구"] = tool_name
            output["매칭_결과"] = payload(await session.call_tool(tool_name, arguments))
            output["안내"] = "질문·제안은 사람의 답변·본인 수락을 기다립니다. 자격 진위를 AI 추론으로 확인하지 않습니다."
            return redact(output, token)
        task_id = args.task_id
        if args.post:
            quote_args = {**selected, "order_id": args.order_id, **task_arguments(args)}
            if args.candidate_ref:
                quote_args["candidate_ref"] = args.candidate_ref
            if args.deadline_at:
                quote_args["deadline_at"] = args.deadline_at
            quote = {"quote_id":args.quote_id} if args.quote_id else payload(await session.call_tool("find_capacity", quote_args))
            if not args.quote_id and quote.get("price_total", args.max_total + 1) > args.max_total:
                raise ConnectorError("견적이 지정한 상한을 넘습니다. 업무를 만들지 않았습니다.")
            task = payload(await session.call_tool("post_task", {"quote_id": quote["quote_id"], "order_id": args.order_id, "client_request_id": args.request_id, "max_total": args.max_total}))
            task_id = task["id"]
            output["업무_생성"] = True
            output["업무"] = task
            output["발주_재시도_정보"] = {"quote_id":quote["quote_id"],"order_id":args.order_id,"client_request_id":args.request_id,"max_total":args.max_total}
        if not task_id:
            output["계약_문맥"] = context or payload(await session.call_tool("get_order_context", {}))
        else:
            deadline = time.monotonic() + args.wait_seconds
            while True:
                task = payload(await session.call_tool("get_status", {"task_id": task_id}))
                if selected.get("project_id") and not _same_work_scope(selected,task):
                    raise ConnectorError("업무의 프로젝트·참여 방식이 현재 입력과 다릅니다.","checkpoint_scope_mismatch")
                output["업무"] = task
                if task["status"] in TERMINAL or time.monotonic() >= deadline:
                    break
                await asyncio.sleep(min(10, max(0, deadline - time.monotonic())))
            if task["status"] == "completed":
                result = payload(await session.call_tool("get_result", {"task_id": task_id}))
                output["검수_결과"] = result
                output["후속_자동행동_허용"] = result.get("quality", {}).get("automation_allowed") is True and result.get("outcome") not in {"unable", "unknown"}
            else:
                output["안내"] = "사람의 수행·검수를 기다리세요. 같은 업무 번호로 --task-id를 지정해 다시 조회할 수 있습니다."
        return redact(output, token)


def parser() -> argparse.ArgumentParser:
    value = argparse.ArgumentParser(description=__doc__)
    value.add_argument("--endpoint", default="https://sonnaru.com/mcp/", help="손나루 HTTPS MCP 주소")
    value.add_argument("--post", action="store_true", help="업무 발주 요청. 발주·예산 예약은 고객 본인 웹에서만 되므로 AI 키로는 서버가 human_confirmation_required로 거부")
    value.add_argument("--site-id", help="허용 장소 번호")
    value.add_argument("--project-id", help="현재 AI 키에 명시적으로 허용된 프로젝트 번호")
    value.add_argument("--work-mode", choices=("remote","on_site","hybrid"), help="원격은 프로젝트만 사용하고 방문·혼합만 장소 권한을 확인")
    value.add_argument("--order-id", help="확인된 계약 발주번호")
    value.add_argument("--max-total", type=int, help="부가세 포함 건당 상한 KRW")
    value.add_argument("--request-id", help="재시도 때 유지할 중복방지키")
    value.add_argument("--quote-id", help="재시도 때 원래 견적 번호를 유지. 요청 ID·발주번호·상한도 동일하게 지정. workflow quote/requote에서는 고객이 sonnaru.com에서 만든 후보 견적 번호를 기록")
    value.add_argument("--task-id", help="이미 요청한 업무 번호")
    value.add_argument("--wait-seconds", type=int, default=0, help="사람 수행·검수 결과를 기다릴 최대 초, 0~3600")
    value.add_argument("--match-action", choices=("prepare", "inspect", "agree", "ask", "evidence", "propose"), help="명시적으로 실행할 협의 동작. ask는 수행자에게 인앱 질문을 전달")
    value.add_argument("--brief-id", help="매칭 협의 번호")
    value.add_argument("--brief-version", type=int, help="최근 조회한 협의 버전")
    value.add_argument("--purpose", help="요청할 기여와 결과의 목적. 개인정보를 넣지 마세요")
    value.add_argument("--deadline-at", help="시간대를 포함한 ISO 8601 납기")
    value.add_argument("--candidate-ref", help="현재 고객·장소 범위에서 유효한 단기 후보 참조")
    value.add_argument("--task-type", choices=("human_task", "notice_display_check"), help="작업 종류. 체크포인트 prepare는 human_task가 기본이며 기존 개별 발주는 안내문 호환을 유지")
    value.add_argument("--task-spec", help="범용 업무의 version=1 JSON 사양 파일. 체크포인트에 원문을 저장하지 않음")
    value.add_argument("--workflow-action", choices=WORKFLOW_ACTIONS, help="체크포인트를 사용하는 명시적 단계. resume은 조회만 하고 발주·연락을 실행하지 않음. agree·ask·refresh·propose와 후보 지정 견적은 고객 본인 웹 단계라 AI 키로는 서버가 human_confirmation_required로 거부")
    value.add_argument("--checkpoint", help="비밀키·답변·사진 없는 로컬 진행 JSON 파일")
    value.add_argument("--client-namespace", help="이 흐름을 구분하는 영문·숫자 이름. 서버의 실제 고객 범위와 함께 검사")
    value.add_argument("--job-draft", help="사용자가 무료 초안에 동의한 뒤 요약 JSON으로 실행. 저장·연락·예약 없음")
    value.add_argument("--job-submit", action="store_true", help="초안을 보여 주고 별도 제출 동의를 받은 뒤 사용. 고객 웹 확인 대기로만 제출")
    value.add_argument("--fit-request-id", help="resume에 표시되는 안정적인 작업 적합성 요청 번호. 참여자 지정·갱신에 사용")
    return value


def main() -> int:
    logging.disable(logging.CRITICAL)
    try:
        args = parser().parse_args()
        token = load_token()
        output = asyncio.run(run(args, token))
        print(json.dumps(output, ensure_ascii=False, indent=2))
        return 0
    except ConnectorError as exc:
        print(f"연결 확인 필요: {exc}", file=sys.stderr)
    except (KeyboardInterrupt, EOFError):
        print("연결을 종료했습니다. 진행 중인 업무는 자동으로 취소되지 않습니다.", file=sys.stderr)
    except Exception:
        print("연결을 완료하지 못했습니다. 서버 상태·키 권한·공식 SDK 버전을 확인하세요. 발주 재시도에는 같은 요청 ID를 사용하세요.", file=sys.stderr)
    return 1


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