build_agent_full.py 23.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
#!/usr/bin/env python3
"""Complete rebuild of reservation conversation flow on clean git HEAD file."""
PATH = 'lib/pages/agent/agent_chat_page.dart'

with open(PATH, 'r') as f:
    c = f.read()

# ===== 1. Enum =====
c = c.replace('enum _CardKind { kpi, tableList, bookingList, orderList, dishRank, plain }',
    'enum _CardKind { kpi, tableList, bookingList, orderList, dishRank, plain, reservationDraft }', 1)

# ===== 2. _AgentCard =====
old = 'class _AgentCard {\n  const _AgentCard({\n    required this.kind,\n    required this.title,\n    required this.items,\n  });\n\n  final _CardKind kind;\n  final String title;\n  final List<Map<String, dynamic>> items;\n}'
new = 'class _AgentCard {\n  const _AgentCard({\n    required this.kind,\n    required this.title,\n    required this.items,\n    this.followUps = const <String>[],\n    this.quickActions = const <String>[],\n  });\n\n  final _CardKind kind;\n  final String title;\n  final List<Map<String, dynamic>> items;\n  final List<String> followUps;\n  final List<String> quickActions;\n}'
c = c.replace(old, new, 1)

# ===== 3. _ChatMessage =====
old2 = 'class _ChatMessage {\n  _ChatMessage({\n    required this.role,\n    required this.text,\n    this.card,\n    this.status = _MessageStatus.done,\n    String? id,\n    DateTime? ts,\n  })  : id = id ?? \'${DateTime.now().microsecondsSinceEpoch}_${role.name}\',\n        ts = ts ?? DateTime.now();\n\n  final String id;\n  final _Role role;\n  String text;\n  _AgentCard? card;\n  _MessageStatus status;\n  DateTime ts;\n}'
new2 = 'class _ChatMessage {\n  _ChatMessage({\n    required this.role,\n    required this.text,\n    this.card,\n    this.status = _MessageStatus.done,\n    this.imagePath,\n    String? id,\n    DateTime? ts,\n  })  : id = id ?? \'${DateTime.now().microsecondsSinceEpoch}_${role.name}\',\n        ts = ts ?? DateTime.now();\n\n  final String id;\n  final _Role role;\n  String text;\n  _AgentCard? card;\n  _MessageStatus status;\n  DateTime ts;\n  final String? imagePath;\n}'
c = c.replace(old2, new2, 1)

# ===== 4. _cardFromJson =====
old3 = '  _AgentCard? _cardFromJson(Map<String, dynamic> json) {\n    final String kind = json[\'kind\']?.toString() ?? \'plain\';\n    return _AgentCard(\n      kind: _cardKindFromName(kind),\n      title: json[\'title\']?.toString() ?? \'\',\n      items: (json[\'items\'] as List? ?? const <dynamic>[])\n          .cast<Map<String, dynamic>>(),\n    );\n  }'
new3 = '  _AgentCard? _cardFromJson(Map<String, dynamic> json) {\n    final String kind = json[\'kind\']?.toString() ?? \'plain\';\n    return _AgentCard(\n      kind: _cardKindFromName(kind),\n      title: json[\'title\']?.toString() ?? \'\',\n      items: (json[\'items\'] as List? ?? const <dynamic>[])\n          .cast<Map<String, dynamic>>(),\n      followUps: (json[\'followUps\'] as List? ?? const <dynamic>[])\n          .whereType<String>()\n          .toList(),\n      quickActions: (json[\'quickActions\'] as List? ?? const <dynamic>[])\n          .whereType<String>()\n          .toList(),\n    );\n  }'
c = c.replace(old3, new3, 1)

# ===== 5. _cardKindFromName =====
c = c.replace("      case 'dish_rank':\n        return _CardKind.dishRank;\n      default:",
    "      case 'dish_rank':\n        return _CardKind.dishRank;\n      case 'reservation_draft':\n        return _CardKind.reservationDraft;\n      default:", 1)

# ===== 6. _cardKindName =====
c = c.replace("      case _CardKind.dishRank:\n        return 'dish_rank';\n      case _CardKind.plain:",
    "      case _CardKind.dishRank:\n        return 'dish_rank';\n      case _CardKind.reservationDraft:\n        return 'reservation_draft';\n      case _CardKind.plain:", 1)

# ===== 7. _toRecords serialization =====
old7 = "                'card': message.card == null\n            ? null\n            : <String, dynamic>{\n                'kind': _cardKindName(message.card!.kind),\n                'title': message.card!.title,\n                'items': message.card!.items,\n              },"
new7 = "                'card': message.card == null\n            ? null\n            : <String, dynamic>{\n                'kind': _cardKindName(message.card!.kind),\n                'title': message.card!.title,\n                'items': message.card!.items,\n                'followUps': message.card!.followUps,\n                'quickActions': message.card!.quickActions,\n              },"
c = c.replace(old7, new7, 1)

# ===== 8. Reservation conversation methods (insert before _usingCloudAsr) =====
insert_marker = '\n  bool _usingCloudAsr = false;'
reservation_block = '''
  /// ---- 预订会话式录入 ----
  ReservationImageParseResult? _pendingReservation;
  bool _reservationAwaitingConfirm = false;

  bool _reservationRequiredComplete(ReservationImageParseResult result) {
    return result.name.isNotEmpty && result.phone.isNotEmpty &&
        result.party.isNotEmpty && result.date.isNotEmpty;
  }

  ReservationImageParseResult _mergeReservation(ReservationImageParseResult old, ReservationImageParseResult next) {
    return ReservationImageParseResult(
      name: next.name.isNotEmpty ? next.name : old.name,
      sex: next.sex.isNotEmpty ? next.sex : old.sex,
      phone: next.phone.isNotEmpty ? next.phone : old.phone,
      party: next.party.isNotEmpty ? next.party : old.party,
      date: next.date.isNotEmpty ? next.date : old.date,
      meal: next.meal.isNotEmpty ? next.meal : old.meal,
      time: next.time.isNotEmpty ? next.time : old.time,
      table: next.table.isNotEmpty ? next.table : old.table,
      remark: next.remark.isNotEmpty ? next.remark : old.remark,
      rawText: next.rawText.isNotEmpty ? next.rawText : old.rawText,
    );
  }

  ReservationImageParseResult _normalizeReservationDate(ReservationImageParseResult result) {
    final DateTime now = DateTime.now();
    String date = result.date.trim();
    if (date.isEmpty) return result;
    if (date == '今天' || date == '今日') {
      date = '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';
    } else if (date == '明天' || date == '明日') {
      final DateTime t = now.add(const Duration(days: 1));
      date = '${t.year}-${t.month.toString().padLeft(2, '0')}-${t.day.toString().padLeft(2, '0')}';
    } else if (date == '后天') {
      final DateTime t = now.add(const Duration(days: 2));
      date = '${t.year}-${t.month.toString().padLeft(2, '0')}-${t.day.toString().padLeft(2, '0')}';
    } else if (RegExp(r'^\\d{1,2}月\\d{1,2}日$').hasMatch(date)) {
      final Match? m = RegExp(r'(\\d{1,2})月(\\d{1,2})日').firstMatch(date);
      if (m != null) {
        final int month = int.parse(m.group(1)!);
        final int day = int.parse(m.group(2)!);
        int year = now.year;
        if (DateTime(year, month, day).isBefore(DateTime(now.year, now.month, now.day))) year++;
        date = '$year-${month.toString().padLeft(2, '0')}-${day.toString().padLeft(2, '0')}';
      }
    }
    return ReservationImageParseResult(name: result.name, sex: result.sex, phone: result.phone,
      party: result.party, date: date, meal: result.meal, time: result.time,
      table: result.table, remark: result.remark, rawText: result.rawText);
  }

  String _reservationIntro(ReservationImageParseResult result) {
    final List<String> parts = <String>[];
    if (result.name.isNotEmpty) parts.add('预订人: ${result.name}');
    if (result.phone.isNotEmpty) parts.add('电话: ${result.phone}');
    if (result.party.isNotEmpty) parts.add('人数: ${result.party}人');
    if (result.date.isNotEmpty) parts.add('日期: ${result.date}');
    if (parts.isEmpty) return '我从信息中没有识别到完整的预订信息,咱们一起补全吧。\\n请告诉我预订人姓名、电话、人数和日期。';
    return '我从信息中识别到:\\n${parts.join('\\n')}\\n\\n如有遗漏,直接回复补充即可。';
  }

  String _reservationSummaryText(ReservationImageParseResult result) {
    final List<String> parts = <String>[];
    if (result.name.isNotEmpty) parts.add('姓名: ${result.name}');
    if (result.phone.isNotEmpty) parts.add('电话: ${result.phone}');
    if (result.party.isNotEmpty) parts.add('人数: ${result.party}人');
    if (result.date.isNotEmpty) parts.add('日期: ${result.date}');
    if (result.meal.isNotEmpty) parts.add('时段: ${result.meal}');
    if (result.time.isNotEmpty) parts.add('到店时间: ${result.time}');
    if (result.table.isNotEmpty) parts.add('桌台: ${result.table}');
    return parts.join('\\n');
  }

  String _nextReservationQuestion(ReservationImageParseResult result) {
    final List<String> missing = <String>[];
    if (result.name.isEmpty) missing.add('预订人姓名');
    if (result.phone.isEmpty) missing.add('手机号');
    if (result.party.isEmpty) missing.add('用餐人数');
    if (result.date.isEmpty) missing.add('预订日期');
    if (missing.isEmpty) return '信息已经齐全啦,确认一下就可以录入。';
    return '还缺${missing.join('、')},直接回复我即可,例如"王先生 13800138000 8人 明晚"。';
  }

  _AgentCard _reservationDraftCard(ReservationImageParseResult result,
      {List<String> quickActions = const <String>[]}) {
    final List<String> actions = quickActions.isNotEmpty ? quickActions
        : const <String>['确认录入', '好了,没问题', '修改信息', '取消'];
    return _AgentCard(
      kind: _CardKind.reservationDraft,
      title: '预订信息草稿',
      items: <Map<String, dynamic>>[
        {'label': '姓名', 'value': result.name.isEmpty ? '待补充' : result.name},
        {'label': '电话', 'value': result.phone.isEmpty ? '待补充' : result.phone},
        {'label': '人数', 'value': result.party.isEmpty ? '待补充' : '${result.party}人'},
        {'label': '日期', 'value': result.date.isEmpty ? '待补充' : result.date},
        if (result.meal.isNotEmpty) {'label': '时段', 'value': result.meal},
        if (result.time.isNotEmpty) {'label': '到店时间', 'value': result.time},
        if (result.table.isNotEmpty) {'label': '桌台', 'value': result.table},
      ],
      quickActions: _reservationAwaitingConfirm ? actions : const <String>[],
    );
  }

  bool _isReservationConfirmText(String text) {
    final String t = text.trim();
    if (RegExp(r'^(确认|确认录入|好了|好的|可以|可以录入|没问题|没问题了|录入|行|对|ok|yes)$', caseSensitive: false).hasMatch(t)) return true;
    if (t.contains('确认') && !t.contains('改') && !t.contains('换') && !t.contains('不是') && !t.contains('错了')) return true;
    if ((t.contains('好了') || t.contains('没问题')) && !t.contains('改') && !t.contains('不是')) return true;
    return false;
  }

  bool _isModificationIntent(String text) {
    final String t = text.trim();
    return t == '修改信息' || t == '修改' || t == '改一下' || t == '改' || t == '我要修改' || t == '需要修改';
  }

  String _describeChanges(ReservationImageParseResult before, ReservationImageParseResult after) {
    final List<String> fields = <String>[];
    if (after.name.isNotEmpty && after.name != before.name) fields.add('姓名');
    if (after.phone.isNotEmpty && after.phone != before.phone) fields.add('手机号');
    if (after.party.isNotEmpty && after.party != before.party) fields.add('人数');
    if (after.date.isNotEmpty && after.date != before.date) fields.add('日期');
    if (after.meal.isNotEmpty && after.meal != before.meal) fields.add('时段');
    if (after.time.isNotEmpty && after.time != before.time) fields.add('到店时间');
    if (after.table.isNotEmpty && after.table != before.table) fields.add('桌台');
    if (fields.isEmpty) return '';
    return fields.join('、');
  }

  Map<String, String> _reservationToFields(ReservationImageParseResult result) {
    return <String, String>{
      'name': result.name, 'sex': result.sex, 'phone': result.phone,
      'party': result.party, 'date': result.date, 'meal': result.meal,
      'time': result.time, 'table': result.table, 'remark': result.remark,
    };
  }

  Future<void> _startReservationConversation(ReservationImageParseResult result, {String? imagePath}) async {
    if (!mounted) return;
    _pendingReservation = _normalizeReservationDate(result);
    _reservationAwaitingConfirm = _reservationRequiredComplete(_pendingReservation!);
    setState(() {
      _messages.add(_ChatMessage(
        role: _Role.user,
        text: imagePath != null && imagePath.isNotEmpty ? '我发来一张预订截图' : '语音录入预订信息',
        imagePath: imagePath,
      ));
      _messages.add(_ChatMessage(
        role: _Role.agent,
        text: _reservationIntro(_pendingReservation!),
        card: _reservationDraftCard(_pendingReservation!),
      ));
    });
    _scrollToBottom();
    _persist();
  }

  Future<void> _handleReservationClarification(String text) async {
    final ReservationImageParseResult? current = _pendingReservation;
    if (current == null || !mounted) return;
    if (text.contains('取消') || text.contains('算了') || text.contains('不用')) {
      _pendingReservation = null;
      _reservationAwaitingConfirm = false;
      setState(() {
        _messages.add(_ChatMessage(role: _Role.user, text: text));
        _messages.add(_ChatMessage(role: _Role.agent, text: '好的,已取消这次预订录入。还想查什么随时问我~'));
      });
      _scrollToBottom(); _persist(); return;
    }
    setState(() { _messages.add(_ChatMessage(role: _Role.user, text: text)); });
    _scrollToBottom(); _persist();

    if (_reservationAwaitingConfirm) {
      if (_isReservationConfirmText(text)) {
        _pendingReservation = null; _reservationAwaitingConfirm = false;
        setState(() { _messages.add(_ChatMessage(role: _Role.agent, text: '好嘞,这就帮你带入预订信息,请在下个页面最后提交一下 👇')); });
        _scrollToBottom(); _persist();
        _openBookingWithFields(_reservationToFields(current));
        return;
      }
      if (_isModificationIntent(text)) {
        setState(() { _messages.add(_ChatMessage(role: _Role.agent,
          text: '好的,请问要修改哪一项?直接告诉我就行,比如"手机号改成138xxxx""姓名改成张三"。',
          card: _reservationDraftCard(current))); });
        _scrollToBottom(); _persist(); return;
      }
      final ReservationImageParseResult parsed = ReservationImageParser.parse(text);
      final bool hasUpdate = parsed.hasAny;
      final ReservationImageParseResult merged = _normalizeReservationDate(_mergeReservation(current, parsed));
      _pendingReservation = merged;
      _reservationAwaitingConfirm = _reservationRequiredComplete(merged);
      final String changed = hasUpdate ? _describeChanges(current, parsed) : '';
      setState(() { _messages.add(_ChatMessage(role: _Role.agent,
        text: hasUpdate
          ? (_reservationAwaitingConfirm ? '已修改$changed,确认无误回复"确认"即可录入。' : '已修改$changed,${_nextReservationQuestion(merged)}')
          : '没有识别到具体要修改的内容,能再说一遍吗?比如"手机号改成138xxxx""姓名改成张三"。',
        card: _reservationDraftCard(merged))); });
      _scrollToBottom(); _persist(); return;
    }

    final ReservationImageParseResult parsed = ReservationImageParser.parse(text);
    final ReservationImageParseResult merged = _normalizeReservationDate(_mergeReservation(current, parsed));
    if (_reservationRequiredComplete(merged)) {
      _pendingReservation = merged; _reservationAwaitingConfirm = true;
      setState(() { _messages.add(_ChatMessage(role: _Role.agent,
        text: '信息已经齐全:\\n${_reservationSummaryText(merged)}\\n\\n确认无误就回复"确认",我直接帮你录入;要修改哪一项也直接告诉我。',
        card: _reservationDraftCard(merged))); });
      _scrollToBottom(); _persist(); return;
    }
    _pendingReservation = merged; _reservationAwaitingConfirm = false;
    setState(() { _messages.add(_ChatMessage(role: _Role.agent,
      text: _nextReservationQuestion(merged), card: _reservationDraftCard(merged))); });
    _scrollToBottom(); _persist();
  }

  void _maybeEnterReservationFlow(String text) {
    final ReservationImageParseResult parsed = ReservationImageParser.parse(text);
    if (parsed.hasAny) _startReservationConversation(parsed);
  }

  List<String> _followUpsFor(_CardKind kind) {
    switch (kind) {
      case _CardKind.kpi: return const <String>['昨天呢?', '近7天统计', '同比环比'];
      case _CardKind.tableList: return const <String>['今晚空桌呢?', '4人可用桌位', '桌位状态'];
      case _CardKind.bookingList: return const <String>['未确认的预订', '预订详情'];
      case _CardKind.orderList: return const <String>['支付状态', '指定桌位订单'];
      case _CardKind.dishRank: return const <String>['销量排行', '销售额排行', '滞销菜品'];
      case _CardKind.reservationDraft:
      case _CardKind.plain: return const <String>[];
    }
  }

  _AgentCard _withFollowUps(_AgentCard card) {
    return _AgentCard(
      kind: card.kind, title: card.title, items: card.items,
      followUps: _followUpsFor(card.kind), quickActions: card.quickActions,
    );
  }
'''

c = c.replace(insert_marker, reservation_block + insert_marker, 1)

# ===== 9. _CardView: add onAction + quickActions buttons =====
old_cv = '''class _CardView extends StatelessWidget {
  const _CardView({required this.card, required this.themeColor});

  final _AgentCard card;
  final Color themeColor;'''
new_cv = '''class _CardView extends StatelessWidget {
  const _CardView({required this.card, required this.themeColor, this.onAction});

  final _AgentCard card;
  final Color themeColor;
  final ValueChanged<String>? onAction;'''
c = c.replace(old_cv, new_cv, 1)

old_detail = '''          if (card.kind != _CardKind.plain) ...[
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text(
                  '点击查看详情',
                  style: TextStyle(fontSize: 10, color: themeColor),
                ),
                const SizedBox(width: 2),
                Icon(Icons.chevron_right, size: 12, color: themeColor),
              ],
            ),
          ],'''
new_detail = '''          if (card.quickActions.isNotEmpty && onAction != null) ...[
            const SizedBox(height: 10),
            Wrap(
              spacing: 6, runSpacing: 6,
              children: card.quickActions.map((String action) {
                final bool isPrimary = action.contains('确认') || action.contains('好了');
                return GestureDetector(
                  onTap: () => onAction!.call(action),
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    decoration: BoxDecoration(
                      color: isPrimary ? themeColor : themeColor.withValues(alpha: 0.10),
                      borderRadius: BorderRadius.circular(16),
                      border: isPrimary ? null : Border.all(color: themeColor.withValues(alpha: 0.25)),
                    ),
                    child: Text(action, style: TextStyle(
                      fontSize: 12, fontWeight: isPrimary ? FontWeight.w600 : FontWeight.w400,
                      color: isPrimary ? Colors.white : themeColor)),
                  ),
                );
              }).toList(),
            ),
          ],
          if (card.kind != _CardKind.plain) ...[
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text('点击查看详情', style: TextStyle(fontSize: 10, color: themeColor)),
                const SizedBox(width: 2),
                Icon(Icons.chevron_right, size: 12, color: themeColor),
              ],
            ),
          ],'''
c = c.replace(old_detail, new_detail, 1)

# ===== 10. _MessageBubble: onAction + imagePath + followUps =====
old_mb = '                child: _CardView(card: message.card!, themeColor: themeColor),'
new_mb = '                child: _CardView(card: message.card!, themeColor: themeColor, onAction: onSuggestion),'
c = c.replace(old_mb, new_mb, 1)

old_img = '            _buildContent(textColor),'
new_img = '''            if (message.imagePath != null && File(message.imagePath!).existsSync()) ...[
              Padding(
                padding: const EdgeInsets.only(bottom: 8),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: Image.file(File(message.imagePath!), width: 180, height: 160, fit: BoxFit.cover),
                ),
              ),
            ],
            _buildContent(textColor),'''
c = c.replace(old_img, new_img, 1)

# Add followUps rendering after card
old_card_block = '''            if (message.card != null) ...[
              const SizedBox(height: 8),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (_) => _AgentCardDetailPage(
                        card: message.card!,
                        themeColor: themeColor,
                      ),
                    ),
                  );
                },
                child: _CardView(card: message.card!, themeColor: themeColor, onAction: onSuggestion),
              ),
            ],'''

new_card_block = '''            if (message.card != null) ...[
              const SizedBox(height: 8),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (_) => _AgentCardDetailPage(
                        card: message.card!,
                        themeColor: themeColor,
                      ),
                    ),
                  );
                },
                child: _CardView(card: message.card!, themeColor: themeColor, onAction: onSuggestion),
              ),
            ],
            if (message.card != null &&
                message.status == _MessageStatus.done &&
                message.card!.followUps.isNotEmpty) ...[
              const SizedBox(height: 8),
              Wrap(
                spacing: 6, runSpacing: 6,
                children: message.card!.followUps.map((String item) {
                  return GestureDetector(
                    onTap: () => onSuggestion(item),
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                      decoration: BoxDecoration(
                        color: themeColor.withValues(alpha: 0.10),
                        borderRadius: BorderRadius.circular(14),
                        border: Border.all(color: themeColor.withValues(alpha: 0.18)),
                      ),
                      child: Text(item, style: TextStyle(fontSize: 12, color: themeColor)),
                    ),
                  );
                }).toList(),
              ),
            ],'''

if old_card_block in c:
    c = c.replace(old_card_block, new_card_block, 1)
else:
    print("WARNING: card block not found for replacement")

with open(PATH, 'w') as f:
    f.write(c)

print(f"SUCCESS: {c.count(chr(10))} lines")