"""Network interruption between the agent and the CMS."""
import os, pathlib, sys, time
sys.path.insert(0, r"C:\taxpilot-ai-work")
for line in pathlib.Path(r"C:\taxpilot-ai-staging\shared\.env").read_text(encoding="utf-8").splitlines():
    line = line.strip()
    if line and not line.startswith("#") and "=" in line:
        k, v = line.split("=", 1)
        os.environ.setdefault(k.strip(), v.strip().strip('"'))

good = os.environ["TAXPILOT_CMS_URL"]

from app.runtime.container import Container
from app import __main__ as entry

import tempfile
doc = pathlib.Path(tempfile.gettempdir()) / "stress-doc.pdf"
doc.write_bytes(b"%PDF-1.4\n% stress harness\ntrailer<</Root 1 0 R>>")

# --- the interruption: an address nothing answers on ---
os.environ["TAXPILOT_CMS_URL"] = "http://127.0.0.1:9"
down = Container()

started = time.monotonic()
refs = []
for i in range(5):
    refs.append(entry.register_arrival(
        down, source="manual", path=doc, filename=f"outage-{i}.pdf",
        mime_type="application/pdf", size_bytes=doc.stat().st_size,
    ))
print(f"   during outage: references returned = {refs.count(None)} of 5 are None")
print(f"   outbox depth  = {len(down.intake_outbox)}")
print(f"   time to refuse 5 = {time.monotonic()-started:.1f}s")

# --- the recovery ---
os.environ["TAXPILOT_CMS_URL"] = good
up = Container()
up.__dict__["intake_outbox"] = down.intake_outbox   # same queue, working CMS

recovery = time.monotonic()
drained = 0
for _ in range(20):
    if len(up.intake_outbox) == 0:
        break
    entry._drain_outbox(up)
    drained += 1

print(f"   after recovery: outbox depth = {len(up.intake_outbox)}, passes = {drained}")
print(f"   recovery time = {time.monotonic()-recovery:.1f}s")
