[{'Text': '      period: "{doc["period"]}",\n      channel: "{doc["channel"]}",\n      domain: "{doc["domain"]}",\n      state: 1,\n      tech: "{tech}",\n      subscribers: {doc["subscribers"]},\n      is_estimate: {str(doc.get("is_estimate", False)).lower()},\n      restated: {str(doc.get("restated", False)).lower()},\n      notes: {f\'"{notes}"\' if doc.get("notes") else "null"},\n      is_archived: false,\n      createdBy: "{created_by}",\n      updatedBy: "{created_by}",\n      date: now,\n      createdAt: now,\n      updatedAt: now\n    }});\n    EJSON.stringify(result.insertedId);\n    """\n    out = _run_mongosh(js)\n    data = json.loads(out) if out else {}\n    if isinstance(data, dict) and "$oid" in data:\n        return data["$oid"]\n    return str(data)\n\n\ndef insert_statistic_safe(\n    operator_id: str,\n    type_val: str,\n    period: str,\n    tech_val: str,\n    channel: str,\n    domain: str,\n    subscribers: int,\n    created_by: str = "gbs-agent",\n    is_estimate: bool = False,\n    restated: bool = False,\n    notes: str | None = None,\n) -> str:\n    """Combined operator lookup + duplicate check + insert in ONE mongosh call.\n\n    Returns JSON with either:\n      {{"ok": true, "insertedId": "..."}}\n      {{"ok": false, "error": "message ..."}}\n\n    Eliminates the 3-call cascade that caused timeouts.\n    """\n    op_esc = lambda s: (s or "").replace("\\\\", "\\\\\\\\").replace(\'"\', \'\\\\"\').replace("\\n", "\\\\n")\n    type_esc = op_esc(type_val)\n    tech_esc = op_esc(tech_val)\n    notes_esc = op_esc(notes) if notes else None\n    by_esc = op_esc(created_by)\n\n    js = f"""\n    const op = db.{OPERATOR_COLLECTION}.findOne({{_id: ObjectId("{operator_id}")}});\n    if (!op) {{ print(EJSON.stringify({{ok: false, error: "Operator not found: {operator_id}"}})); exit(0); }}\n\n    const techMatch = (op.technologies || []).find(\n      t => t.toLowerCase() === "{tech_esc}".toLowerCase()\n    );\n    if (!techMatch) {{\n      print(EJSON.stringify({{ok: false, error: "Tech \'{tech_esc}\' not valid for \'" + op.name + "\'. Valid: " + JSON.stringify(op.technologies)}}));\n      exit(0);\n    }}\n\n    const existing = db.{STATISTICS_COLLECTION}.find({{operatorId: ObjectId("{operator_id}"), period: "{period}"}}).toArray();\n    const dup = existing.find(s =>\n      s.type === "{type_esc}" && s.tech === techMatch && s.channel === "{channel}" && s.domain === "{domain}"\n    );\n    if (dup) {{\n      print(EJSON.stringify({{ok: false, error: "Duplicate: statistic already exists for {type_esc}/" + techMatch + "/{channel}/{domain} in {period} (id=" + dup._id + ", state=" + dup.state + ")"}}));\n      exit(0);\n    }}\n\n    const now = new Date();\n    const result = db.{STATISTICS_COLLECTION}.insertOne({{\n      type: "{type_esc}",\n      country: op.country,\n      operator: op.name,\n      operatorId: ObjectId("{operator_id}"),\n      period: "{period}",\n      channel: "{channel}",\n      domain: "{domain}",\n      state: 1,\n      tech: techMatch,\n      subscribers: {subscribers},\n      is_estimate: {str(is_estimate).lower()},\n      restated: {str(restated).lower()},\n      notes: {"null" if notes_esc is None else f\'"{notes_esc}"\'},\n      is_archived: false,\n      createdBy: "{by_esc}",\n      updatedBy: "{by_esc}",\n      date: now,\n      createdAt: now,\n      updatedAt: now\n    }});\n    print(EJSON.stringify({{ok: true, insertedId: result.insertedId, operator: op.name, country: op.country, tech: techMatch}}));\n    """\n    out = _run_mongosh(js, timeout=30)\n    data = json.loads(out) if out else {"ok": False, "error": "No output from mongosh"}\n    return json.dumps(data)\n\n\ndef insert_one_source(doc: dict) -> str:\n    """Insert one Source document. Returns inserted ObjectId string."""\n    oid = doc["operatorId"]\n'}]