"""Apply the 10 send_result -> send edits in the 5 other src/ files (Phase 2)."""
from __future__ import annotations

import sys
from pathlib import Path

FILES = [
 "src/app_controller.py",
 "src/conductor_tech_lead.py",
 "src/mcp_client.py",
 "src/multi_agent_conductor.py",
 "src/orchestrator_pm.py",
]

EDITS: dict[str, list[tuple[str, str]]] = {
 "src/app_controller.py": [
  ("result = ai_client.send_result(context_to_send,", "result = ai_client.send(context_to_send,"),
  ("result = ai_client.send_result(\n", "result = ai_client.send(\n"),
 ],
 "src/conductor_tech_lead.py": [
  (" - Uses ai_client.send_result() for LLM communication", " - Uses ai_client.send() for LLM communication"),
  ("result = ai_client.send_result(\n", "result = ai_client.send(\n"),
  ("print(f\"[conductor_tech_lead] send_result failed: {_msg}\")", "print(f\"[conductor_tech_lead] send failed: {_msg}\")"),
 ],
 "src/mcp_client.py": [
  ("'src.ai_client.send_result'", "'src.ai_client.send'"),
 ],
 "src/multi_agent_conductor.py": [
  ("result = ai_client.send_result(\n", "result = ai_client.send(\n"),
  ("print(f\"[MMA] Worker send_result failed for {ticket.id}: {err_msg}\")", "print(f\"[MMA] Worker send failed for {ticket.id}: {err_msg}\")"),
 ],
 "src/orchestrator_pm.py": [
  ("result = ai_client.send_result(\n", "result = ai_client.send(\n"),
  ("print(f\"[orchestrator_pm] send_result failed: {_msg}\")", "print(f\"[orchestrator_pm] send failed: {_msg}\")"),
 ],
}


def main() -> int:
 total = 0
 for rel in FILES:
  p = Path(rel)
  with p.open("r", encoding="utf-8", newline="") as f:
   content = f.read()
  has_crlf = "\r\n" in content
  nl = "\r\n" if has_crlf else "\n"
  edits = [(o.replace("\n", nl), n.replace("\n", nl)) for o, n in EDITS[rel]]
  new_content = content
  applied = 0
  for old, new in edits:
   if old in new_content:
    new_content = new_content.replace(old, new, 1)
    applied += 1
   else:
    print(f"NOT FOUND in {rel}: {old[:80]!r}", file=sys.stderr)
  if applied != len(edits):
   print(f"Only applied {applied}/{len(edits)} edits in {rel}. ABORTING.", file=sys.stderr)
   return 1
  with p.open("w", encoding="utf-8", newline="") as f:
   f.write(new_content)
  remaining = new_content.count("send_result")
  print(f"{rel}: applied {applied}/{len(edits)}, remaining={remaining}")
  total += applied
 print(f"Total: {total} edits applied")
 return 0


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