All files / generators/pipeline fetch-stage.ts

78.79% Statements 457/580
73.2% Branches 347/474
80.9% Functions 89/110
79.41% Lines 409/515

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014                                                                                                                        8x     8x     8x                                             18x 18x 18x 18x         18x 18x                       74x 19x 18x 4x 4x     14x       5x 4x 4x         77x 77x 77x                   44x 44x             44x 44x 14x 14x 14x                       19x                 2x         8x                               55x 5x     5x   50x 50x 33x 33x   17x 17x                           20x 20x   1x 1x                           34x 34x   33x 33x 33x 33x 33x                                                   192x   112x 34x 34x     112x 13x           112x                           9x         9x                                             13x                                                                                                 10x 10x 10x 10x     10x                             1x 1x 1x                                               61x                                 170x       44x         44x                                 22x       9x         9x                                                         14x 14x 2x 2x   12x 12x 12x 2x 2x   9x 9x     14x     14x     14x   14x 14x                   14x         14x   1x 1x 1x                                             17x 17x 2x 2x   15x 15x 15x 1x 1x   13x 13x 156x 13x 13x 13x 13x 13x 13x 13x     13x     13x 13x 13x 13x 13x                                   13x                       13x     13x   1x 1x 1x                                   9x 6x 6x 12x               3x 2x     2x 4x                   1x   1x     1x                           1x             1x 1x 6x     1x     1x     1x 1x 1x   1x                                       3x 2x 2x 2x       1x   1x 1x 1x                         3x 2x 2x 2x       1x   1x 1x 1x                         3x 2x 2x 2x       1x   1x 1x 1x                               3x 1x 1x 1x           1x 1x 1x                                           10x 10x 1x 1x   9x 9x 9x 1x 1x   6x 6x 6x 2x   4x 4x       7x   4x           10x               10x     10x   2x 2x 2x                             13x 13x 3x 3x 2x       3x                                     13x                     13x 13x   12x   2x 2x 2x 2x       1x   1x 1x     2x 2x 2x 2x       1x   1x 1x     2x 2x   2x                 2x 2x           2x                                   13x 5x 5x 5x   5x                 4x 3x                             3x 3x 4x                         1x 1x   2x                               13x 5x 5x 5x   5x               4x 3x                   3x 3x 3x               1x 1x   2x                               13x 5x 5x 5x   5x               4x 3x                   3x 3x 3x               1x 1x   2x                               12x 4x 4x 4x   4x                 3x 2x                   2x 1x 2x                 1x 1x   3x                                             5x               5x 5x         5x 5x         5x 5x         5x 5x       5x   5x 4x 4x   5x 4x 4x   5x 4x 4x   5x 5x 5x     5x                           14x   6x 4x       6x   3x       3x   2x     2x   14x   3x                           14x                       13x   5x 3x       5x   2x                       2x   1x 13x   13x   2x                 13x                             14x 3x 3x 3x       2x 1x 1x   1x 1x 1x                                                                                           5x 4x 4x 4x 4x 5x             5x 8x   1x                                                                                               3x 1x 1x 1x 1x           1x 1x 1x                             3x 1x 1x 1x 1x                 1x 1x 1x                             3x 1x 1x 1x 1x                 1x 1x 1x                             2x                                         10x 6x 6x 6x 5x       5x 5x                   5x   1x 1x 1x                             2x                                                     1x                                                     1x                                                     1x                                                     1x                                                     1x                                                     1x                                                     1x                                                         7x 2x 1x     1x   1x           1x 1x                                                   27x 27x 9x 9x 1x       19x 3x 3x 3x                                                                                                                                  
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Generators/Pipeline/FetchStage
 * @description MCP data-fetching pipeline stage with circuit breaker protection.
 *
 * MCP-facing functions accept an explicit `client` argument instead of reading
 * module-level state, making them straightforward to unit-test with a mock
 * client.  The {@link loadFeedDataFromFile} and {@link loadEPFeedDataFromFile}
 * helpers introduce filesystem I/O to load pre-fetched feed JSON produced by
 * agentic workflows.
 *
 * The {@link CircuitBreaker} prevents cascading failures when the MCP server
 * is degraded: after {@link CircuitBreakerOptions.failureThreshold} consecutive
 * errors the circuit opens and subsequent calls short-circuit immediately.
 */
 
import fs from 'fs';
import type { EuropeanParliamentMCPClient } from '../../mcp/ep-mcp-client.js';
import { getEPMCPClient } from '../../mcp/ep-mcp-client.js';
import type {
  WeekAheadData,
  DateRange,
  CommitteeData,
  MCPToolResult,
  VotingRecord,
  VotingPattern,
  VotingAnomaly,
  MotionsQuestion,
  LegislativeDocument,
  AdoptedTextFeedItem,
  EventFeedItem,
  ProcedureFeedItem,
  MEPFeedItem,
  DocumentFeedItem,
  QuestionFeedItem,
  DeclarationFeedItem,
  CorporateBodyFeedItem,
  BreakingNewsFeedData,
  EPFeedData,
  FeedTimeframe,
} from '../../types/index.js';
import {
  parsePlenarySessions,
  parseCommitteeMeetings,
  parseLegislativeDocuments,
  parseLegislativePipeline,
  parseParliamentaryQuestions,
  parseEPEvents,
  PLACEHOLDER_EVENTS,
} from '../week-ahead-content.js';
import { applyCommitteeInfo, applyDocuments, applyEffectiveness } from '../committee-helpers.js';
import { getMotionsFallbackData } from '../motions-content.js';
import { escapeHTML } from '../../utils/file-utils.js';
import type { PipelineData } from '../propositions-content.js';
 
// ─── Shared string constants ─────────────────────────────────────────────────
 
/** Log prefix for MCP fetch operations */
const MCP_FETCH_PREFIX = '  📡';
 
/** Warning prefix for MCP failures */
const WARN_PREFIX = '  ⚠️';
 
/** Info prefix for fallback messages */
const INFO_PREFIX = '  ℹ️';
 
// ─── Circuit Breaker ─────────────────────────────────────────────────────────
 
/** Possible circuit breaker states */
export type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
 
/** Constructor options for {@link CircuitBreaker} */
export interface CircuitBreakerOptions {
  /** Consecutive failures before opening the circuit (default: 3) */
  failureThreshold?: number | undefined;
  /** Milliseconds to wait before probing recovery (default: 60 000) */
  resetTimeoutMs?: number | undefined;
}
 
/**
 * Circuit breaker preventing cascading MCP failures.
 *
 * - **CLOSED** — normal operation; all requests pass through.
 * - **OPEN** — fast-fail; requests are rejected for `resetTimeoutMs` ms.
 * - **HALF_OPEN** — probe state; one request is allowed to test recovery.
 */
export class CircuitBreaker {
  private state: CircuitState = 'CLOSED';
  private consecutiveFailures = 0;
  private nextAttemptAt = 0;
  private halfOpenProbeInFlight = false;
  private readonly failureThreshold: number;
  private readonly resetTimeoutMs: number;
 
  constructor(options: CircuitBreakerOptions = {}) {
    this.failureThreshold = options.failureThreshold ?? 3;
    this.resetTimeoutMs = options.resetTimeoutMs ?? 60_000;
  }
 
  /**
   * Whether a request may proceed given the current circuit state.
   *
   * In HALF_OPEN state only a single probe is allowed at a time; subsequent
   * calls return `false` until the in-flight probe records success or failure.
   *
   * @returns `true` when the circuit is CLOSED, or HALF_OPEN with no probe in flight
   */
  canRequest(): boolean {
    if (this.state === 'CLOSED') return true;
    if (this.state === 'OPEN') {
      if (Date.now() >= this.nextAttemptAt) {
        this.state = 'HALF_OPEN';
        this.halfOpenProbeInFlight = false;
        // Fall through to HALF_OPEN probe logic below
      } else {
        return false;
      }
    }
    // HALF_OPEN: allow exactly one probe in flight at a time
    if (this.halfOpenProbeInFlight) return false;
    this.halfOpenProbeInFlight = true;
    return true;
  }
 
  /** Record a successful request and close the circuit */
  recordSuccess(): void {
    this.consecutiveFailures = 0;
    this.halfOpenProbeInFlight = false;
    this.state = 'CLOSED';
  }
 
  /**
   * Record a failed request.
   *
   * - When in **HALF_OPEN** the circuit re-opens immediately (the probe failed).
   * - When in **CLOSED** the circuit opens only once the failure threshold is reached.
   */
  recordFailure(): void {
    this.halfOpenProbeInFlight = false;
    Iif (this.state === 'HALF_OPEN') {
      // Probe failed — immediately re-open and back off again
      this.state = 'OPEN';
      this.nextAttemptAt = Date.now() + this.resetTimeoutMs;
      console.warn('⚡ Circuit breaker re-OPEN after HALF_OPEN probe failure');
      return;
    }
    this.consecutiveFailures++;
    if (this.consecutiveFailures >= this.failureThreshold) {
      this.state = 'OPEN';
      this.nextAttemptAt = Date.now() + this.resetTimeoutMs;
      console.warn(
        `⚡ Circuit breaker OPEN after ${this.consecutiveFailures} consecutive failures`
      );
    }
  }
 
  /**
   * Return the current circuit state.
   *
   * @returns Current circuit state
   */
  getState(): CircuitState {
    return this.state;
  }
 
  /**
   * Return current statistics for observability.
   *
   * @returns Snapshot of state and consecutive failure count
   */
  getStats(): Readonly<{ state: CircuitState; consecutiveFailures: number }> {
    return { state: this.state, consecutiveFailures: this.consecutiveFailures };
  }
}
 
/** Module-level circuit breaker shared across all MCP fetch operations */
export const mcpCircuitBreaker = new CircuitBreaker();
 
/**
 * Execute a single MCP API call through the module-level circuit breaker.
 * Short-circuits with `fallback` whenever the circuit breaker is not
 * accepting requests (for example when OPEN, or in HALF_OPEN with no
 * probe slots available).
 * Records success or failure after each call, opening the circuit when
 * {@link CircuitBreakerOptions.failureThreshold} consecutive failures occur.
 *
 * @param fn - Async factory that performs the MCP call
 * @param fallback - Value returned when the circuit is not accepting requests
 * @param context - Label used in warning messages
 * @returns Result of `fn` or `fallback`
 */
async function callMCP<T>(fn: () => Promise<T>, fallback: T, context: string): Promise<T> {
  if (!mcpCircuitBreaker.canRequest()) {
    console.warn(
      `${WARN_PREFIX} Circuit breaker not accepting requests (${mcpCircuitBreaker.getState()}) — skipping ${context}`
    );
    return fallback;
  }
  try {
    const result = await fn();
    mcpCircuitBreaker.recordSuccess();
    return result;
  } catch (error) {
    mcpCircuitBreaker.recordFailure();
    throw error;
  }
}
 
// ─── Internal helpers ─────────────────────────────────────────────────────────
 
/**
 * Parse JSON text, returning `null` and logging a warning on parse failure.
 *
 * @param text - Raw JSON string
 * @param context - Label used in the warning message
 * @returns Parsed value or null
 */
function parseJSON<T>(text: string, context: string): T | null {
  try {
    return JSON.parse(text) as T;
  } catch {
    console.warn(`${WARN_PREFIX} Failed to parse JSON for ${context}`);
    return null;
  }
}
 
/** Base shape for feed items that carry a date field */
type DatedFeedItem = { date: string };
 
/**
 * Normalize a feed-item date into canonical UTC `YYYY-MM-DD` form.
 *
 * @param value - Raw date string from MCP or a prefetched feed file
 * @returns Canonical date string, or undefined when the value is missing/invalid
 */
function normalizeFeedItemDate(value: string): string | undefined {
  const trimmed = value.trim();
  if (trimmed === '') return undefined;
 
  const directDate = trimmed.slice(0, 10);
  Eif (directDate.length === 10) {
    const direct = new Date(`${directDate}T00:00:00Z`);
    Eif (!Number.isNaN(direct.getTime())) {
      return directDate;
    }
  }
 
  const parsed = new Date(trimmed);
  if (Number.isNaN(parsed.getTime())) return undefined;
 
  const parts = parsed.toISOString().split('T');
  return parts[0];
}
 
/**
 * Filter dated feed items to an inclusive UTC date window.
 *
 * Items without a parseable `date` are dropped when a window is supplied.
 *
 * @param items - Feed items to filter
 * @param dateRange - Inclusive UTC window, or undefined to keep all items
 * @param label - Human-readable label used in logs
 * @returns Filtered array
 */
function filterFeedItemsByDateRange<T extends DatedFeedItem>(
  items: readonly T[],
  dateRange: DateRange | undefined,
  label: string
): T[] {
  if (!dateRange) return [...items];
 
  const filtered = items.filter((item) => {
    const normalized = normalizeFeedItemDate(item.date);
    return normalized !== undefined && normalized >= dateRange.start && normalized <= dateRange.end;
  });
 
  if (filtered.length !== items.length) {
    console.log(
      `${INFO_PREFIX} Filtered ${label} to ${filtered.length}/${items.length} items within ` +
        `${dateRange.start}..${dateRange.end}`
    );
  }
 
  return filtered;
}
 
/**
 * Apply a date-range filter across all breaking-news feed arrays.
 *
 * @param feedData - Feed data to filter
 * @param dateRange - Inclusive UTC window, or undefined to keep all items
 * @returns Filtered feed payload
 */
function filterBreakingNewsFeedDataByDateRange(
  feedData: BreakingNewsFeedData,
  dateRange: DateRange | undefined
): BreakingNewsFeedData {
  const filteredMEPUpdates = filterFeedItemsByDateRange(
    feedData.mepUpdates,
    dateRange,
    'MEP updates'
  );
  return {
    adoptedTexts: filterFeedItemsByDateRange(feedData.adoptedTexts, dateRange, 'adopted texts'),
    events: filterFeedItemsByDateRange(feedData.events, dateRange, 'events'),
    procedures: filterFeedItemsByDateRange(feedData.procedures, dateRange, 'procedures'),
    mepUpdates: filteredMEPUpdates,
    // When a date-range filter is applied the API-reported total covers the full
    // feed window, not the filtered subset — clear it to avoid a misleading
    // truncation note ("showing 10 of 525" on a single-day slice).
    totalMEPUpdates: dateRange === undefined ? feedData.totalMEPUpdates : undefined,
  };
}
 
/**
 * Apply a date-range filter across all comprehensive EP feed arrays.
 *
 * @param feedData - Feed data to filter
 * @param dateRange - Inclusive UTC window, or undefined to keep all items
 * @returns Filtered feed payload
 */
function filterEPFeedDataByDateRange(
  feedData: EPFeedData,
  dateRange: DateRange | undefined
): EPFeedData {
  return {
    adoptedTexts: filterFeedItemsByDateRange(feedData.adoptedTexts, dateRange, 'adopted texts'),
    events: filterFeedItemsByDateRange(feedData.events, dateRange, 'events'),
    procedures: filterFeedItemsByDateRange(feedData.procedures, dateRange, 'procedures'),
    mepUpdates: filterFeedItemsByDateRange(feedData.mepUpdates, dateRange, 'MEP updates'),
    documents: filterFeedItemsByDateRange(feedData.documents, dateRange, 'documents'),
    plenaryDocuments: filterFeedItemsByDateRange(
      feedData.plenaryDocuments,
      dateRange,
      'plenary documents'
    ),
    committeeDocuments: filterFeedItemsByDateRange(
      feedData.committeeDocuments,
      dateRange,
      'committee documents'
    ),
    plenarySessionDocuments: filterFeedItemsByDateRange(
      feedData.plenarySessionDocuments,
      dateRange,
      'plenary session documents'
    ),
    externalDocuments: filterFeedItemsByDateRange(
      feedData.externalDocuments,
      dateRange,
      'external documents'
    ),
    questions: filterFeedItemsByDateRange(feedData.questions, dateRange, 'questions'),
    declarations: filterFeedItemsByDateRange(feedData.declarations, dateRange, 'declarations'),
    corporateBodies: filterFeedItemsByDateRange(
      feedData.corporateBodies,
      dateRange,
      'corporate bodies'
    ),
  };
}
 
/**
 * Compute an inclusive UTC date window ending on `endDate`.
 *
 * @param endDate - Inclusive UTC end date in `YYYY-MM-DD` form
 * @param lookbackDays - Number of calendar days to subtract for the start date
 * @param context - Label used in error messages
 * @returns Inclusive date range
 */
export function computeRollingDateRange(
  endDate: string,
  lookbackDays: number,
  context: string
): DateRange {
  const startDate = new Date(`${endDate}T00:00:00Z`);
  startDate.setUTCDate(startDate.getUTCDate() - lookbackDays);
  const startDateParts = startDate.toISOString().split('T');
  Iif (!startDateParts[0]) {
    throw new Error(`Invalid date format generated for ${context}`);
  }
  return { start: startDateParts[0], end: endDate };
}
 
// ─── MCP client initialisation ───────────────────────────────────────────────
 
/**
 * Attempt to connect to the European Parliament MCP server.
 * Returns `null` (with a warning) if the connection fails or MCP is disabled.
 *
 * @param useMCP - Whether MCP should be used at all
 * @returns Connected client or null
 */
export async function initializeMCPClient(
  useMCP: boolean
): Promise<EuropeanParliamentMCPClient | null> {
  Eif (!useMCP) {
    console.log(`${INFO_PREFIX} MCP client disabled via USE_EP_MCP=false`);
    return null;
  }
  try {
    console.log('🔌 Attempting to connect to European Parliament MCP Server...');
    const client = await getEPMCPClient();
    console.log('✅ MCP client connected successfully');
    return client;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn('⚠️ Could not connect to MCP server:', message);
    console.warn('⚠️ Falling back to placeholder content');
    return null;
  }
}
 
// ─── Pre-fetched feed data loading ───────────────────────────────────────────
 
/**
 * Check whether a value is a non-null, non-array plain object.
 *
 * @param v - Value to check
 * @returns True when v is a plain object
 */
function isPlainObject(v: unknown): v is Record<string, unknown> {
  return typeof v === 'object' && v !== null && !Array.isArray(v);
}
 
/**
 * Sanitize an array of raw items into feed items with title-based required fields.
 * Filters out non-objects and coerces `id`, `title`, `date` to strings.
 *
 * Uses `as unknown as T` because the spread preserves optional properties from
 * the source JSON while the explicit field assignments guarantee the required
 * base fields — TypeScript cannot infer this mixed provenance automatically.
 *
 * @param items - Raw array of unknown values from JSON
 * @returns Sanitized array of typed feed items
 */
function sanitizeTitleItems<T extends { id: string; title: string; date: string }>(
  items: readonly unknown[]
): T[] {
  return items
    .filter(isPlainObject)
    .filter(
      (item) =>
        (item['id'] !== undefined && item['id'] !== null) ||
        (item['title'] !== undefined && item['title'] !== null)
    )
    .map(
      (item) =>
        ({
          ...item,
          id: String(item['id'] ?? ''),
          title: String(item['title'] ?? ''),
          date: String(item['date'] ?? ''),
        }) as unknown as T
    );
}
 
/**
 * Sanitize an array of raw items into MEP feed items.
 * Filters out non-objects and coerces `id`, `name`, `date` to strings.
 *
 * @param items - Raw array of unknown values from JSON
 * @returns Sanitized array of MEP feed items
 */
function sanitizeMEPItems(items: readonly unknown[]): MEPFeedItem[] {
  return items
    .filter(isPlainObject)
    .filter(
      (item) =>
        (item['id'] !== undefined && item['id'] !== null) ||
        (item['name'] !== undefined && item['name'] !== null)
    )
    .map(
      (item) =>
        ({
          ...item,
          id: String(item['id'] ?? ''),
          name: String(item['name'] ?? ''),
          date: String(item['date'] ?? ''),
        }) as unknown as MEPFeedItem
    );
}
 
/**
 * Load pre-fetched feed data from a JSON file on disk.
 *
 * Agentic workflows fetch EP data via framework MCP tools but the TypeScript
 * generator cannot access those tools directly.  The workflow saves the MCP
 * results to a JSON file and the generator reads them via this function,
 * avoiding the need to manually construct article HTML.
 *
 * The file must contain a JSON object. The optional keys
 * `adoptedTexts`, `events`, `procedures`, and `mepUpdates` are treated as
 * arrays and default to empty arrays when missing (an empty object `{}` is valid).
 *
 * @param filePath - Absolute or relative path to the JSON file
 * @param dateRange - Optional inclusive UTC window for filtering loaded items
 * @returns Parsed {@link BreakingNewsFeedData}, or `undefined` on any error
 */
export function loadFeedDataFromFile(
  filePath: string,
  dateRange?: DateRange
): BreakingNewsFeedData | undefined {
  try {
    if (!fs.existsSync(filePath)) {
      console.warn(`${WARN_PREFIX} Feed data file not found: ${filePath}`);
      return undefined;
    }
    const raw = fs.readFileSync(filePath, 'utf-8');
    const parsed: unknown = JSON.parse(raw);
    if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
      console.warn(`${WARN_PREFIX} Feed data file must contain a JSON object`);
      return undefined;
    }
    const obj = parsed as Record<string, unknown>;
    const adoptedTexts = sanitizeTitleItems<AdoptedTextFeedItem>(
      Array.isArray(obj['adoptedTexts']) ? obj['adoptedTexts'] : []
    );
    const events = sanitizeTitleItems<EventFeedItem>(
      Array.isArray(obj['events']) ? obj['events'] : []
    );
    const procedures = sanitizeTitleItems<ProcedureFeedItem>(
      Array.isArray(obj['procedures']) ? obj['procedures'] : []
    );
    const mepUpdates = sanitizeMEPItems(Array.isArray(obj['mepUpdates']) ? obj['mepUpdates'] : []);
    const totalMEPUpdates =
      typeof obj['totalMEPUpdates'] === 'number' ? obj['totalMEPUpdates'] : undefined;
    const filteredData = filterBreakingNewsFeedDataByDateRange(
      {
        adoptedTexts,
        events,
        procedures,
        mepUpdates,
        totalMEPUpdates,
      },
      dateRange
    );
    console.log(
      `${INFO_PREFIX} Loaded feed data from file: ` +
        `${filteredData.adoptedTexts.length} adopted texts, ${filteredData.events.length} events, ` +
        `${filteredData.procedures.length} procedures, ${filteredData.mepUpdates.length} MEP updates`
    );
    return filteredData;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} Failed to load feed data from file: ${message}`);
    return undefined;
  }
}
 
/**
 * Load pre-fetched comprehensive EP feed data from a JSON file on disk.
 *
 * Agentic workflows fetch EP data via framework MCP tools but the TypeScript
 * generator cannot access those tools directly.  The workflow saves the MCP
 * results to a JSON file and the generator reads them via this function,
 * avoiding the need to manually construct article HTML.
 *
 * The file must contain a JSON object with EP feed data keys.
 * Missing keys default to empty arrays.
 *
 * @param filePath - Absolute or relative path to the JSON file
 * @param dateRange - Optional inclusive UTC window for filtering loaded items
 * @returns Parsed {@link EPFeedData}, or `undefined` on any error
 */
export function loadEPFeedDataFromFile(
  filePath: string,
  dateRange?: DateRange
): EPFeedData | undefined {
  try {
    if (!fs.existsSync(filePath)) {
      console.warn(`${WARN_PREFIX} EP feed data file not found: ${filePath}`);
      return undefined;
    }
    const raw = fs.readFileSync(filePath, 'utf-8');
    const parsed: unknown = JSON.parse(raw);
    if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
      console.warn(`${WARN_PREFIX} EP feed data file must contain a JSON object`);
      return undefined;
    }
    const obj = parsed as Record<string, unknown>;
    const safeArray = (key: string): readonly unknown[] =>
      Array.isArray(obj[key]) ? (obj[key] as unknown[]) : [];
    const adoptedTexts = sanitizeTitleItems<AdoptedTextFeedItem>(safeArray('adoptedTexts'));
    const events = sanitizeTitleItems<EventFeedItem>(safeArray('events'));
    const procedures = sanitizeTitleItems<ProcedureFeedItem>(safeArray('procedures'));
    const mepUpdates = sanitizeMEPItems(safeArray('mepUpdates'));
    const documents = sanitizeTitleItems<DocumentFeedItem>(safeArray('documents'));
    const plenaryDocuments = sanitizeTitleItems<DocumentFeedItem>(safeArray('plenaryDocuments'));
    const committeeDocuments = sanitizeTitleItems<DocumentFeedItem>(
      safeArray('committeeDocuments')
    );
    const plenarySessionDocuments = sanitizeTitleItems<DocumentFeedItem>(
      safeArray('plenarySessionDocuments')
    );
    const externalDocuments = sanitizeTitleItems<DocumentFeedItem>(safeArray('externalDocuments'));
    const questions = sanitizeTitleItems<QuestionFeedItem>(safeArray('questions'));
    const declarations = sanitizeTitleItems<DeclarationFeedItem>(safeArray('declarations'));
    const corporateBodies = sanitizeTitleItems<CorporateBodyFeedItem>(safeArray('corporateBodies'));
    const filteredData = filterEPFeedDataByDateRange(
      {
        adoptedTexts,
        events,
        procedures,
        mepUpdates,
        documents,
        plenaryDocuments,
        committeeDocuments,
        plenarySessionDocuments,
        externalDocuments,
        questions,
        declarations,
        corporateBodies,
      },
      dateRange
    );
    const totalItems =
      filteredData.adoptedTexts.length +
      filteredData.events.length +
      filteredData.procedures.length +
      filteredData.mepUpdates.length +
      filteredData.documents.length +
      filteredData.plenaryDocuments.length +
      filteredData.committeeDocuments.length +
      filteredData.plenarySessionDocuments.length +
      filteredData.externalDocuments.length +
      filteredData.questions.length +
      filteredData.declarations.length +
      filteredData.corporateBodies.length;
    console.log(
      `${INFO_PREFIX} Loaded EP feed data from file: ${totalItems} total items across 12 keys`
    );
    return filteredData;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} Failed to load EP feed data from file: ${message}`);
    return undefined;
  }
}
 
// ─── Week-Ahead fetches ──────────────────────────────────────────────────────
 
/**
 * Fetch aggregated week-ahead data from multiple MCP sources in parallel.
 * Returns placeholder data when the client is unavailable.
 *
 * @param client - MCP client or null
 * @param dateRange - Date range for the week-ahead period
 * @returns Aggregated week-ahead data
 */
export async function fetchWeekAheadData(
  client: EuropeanParliamentMCPClient | null,
  dateRange: DateRange
): Promise<WeekAheadData> {
  if (!client) {
    console.log(`${INFO_PREFIX} MCP unavailable — using placeholder events`);
    return {
      events: PLACEHOLDER_EVENTS.map((e) => ({ ...e, date: dateRange.start })),
      committees: [],
      documents: [],
      pipeline: [],
      questions: [],
    };
  }
 
  if (!mcpCircuitBreaker.canRequest()) {
    console.warn(
      `${WARN_PREFIX} Circuit breaker not accepting requests (${mcpCircuitBreaker.getState()}) — using placeholder events`
    );
    return {
      events: PLACEHOLDER_EVENTS.map((e) => ({ ...e, date: dateRange.start })),
      committees: [],
      documents: [],
      pipeline: [],
      questions: [],
    };
  }
 
  // Record whether we entered as a HALF_OPEN probe so any rejection triggers
  // an immediate re-open (normal circuit-breaker probe semantics).
  const wasHalfOpen = mcpCircuitBreaker.getState() === 'HALF_OPEN';
 
  console.log(`${MCP_FETCH_PREFIX} Fetching week-ahead data from MCP (parallel)...`);
 
  const [plenarySessions, committeeInfo, documents, pipeline, questions, epEvents] =
    await Promise.allSettled([
      client.getPlenarySessions({ startDate: dateRange.start, endDate: dateRange.end, limit: 50 }),
      client.getCommitteeInfo({ limit: 20 }),
      client.searchDocuments({ query: 'parliament', limit: 20 }),
      client.monitorLegislativePipeline({
        dateFrom: dateRange.start,
        dateTo: dateRange.end,
        status: 'ACTIVE',
        limit: 20,
      }),
      client.getParliamentaryQuestions({ startDate: dateRange.start, limit: 20 }),
      client.getEvents({ dateFrom: dateRange.start, dateTo: dateRange.end, limit: 20 }),
    ]);
 
  const allFailed = [
    plenarySessions,
    committeeInfo,
    documents,
    pipeline,
    questions,
    epEvents,
  ].every((r) => r.status === 'rejected');
  const anyFailed = [plenarySessions, committeeInfo, documents, pipeline, questions, epEvents].some(
    (r) => r.status === 'rejected'
  );
  // In HALF_OPEN any single rejection means the probe failed — re-open immediately.
  Iif (allFailed || (wasHalfOpen && anyFailed)) {
    mcpCircuitBreaker.recordFailure();
  } else {
    mcpCircuitBreaker.recordSuccess();
  }
 
  const plenaryEvents = parsePlenarySessions(plenarySessions, dateRange.start);
  const additionalEvents = parseEPEvents(epEvents, dateRange.start);
  const events = [...plenaryEvents, ...additionalEvents];
 
  return {
    events: events.length > 0 ? events : [{ ...PLACEHOLDER_EVENTS[0]!, date: dateRange.start }],
    committees: parseCommitteeMeetings(committeeInfo, dateRange.start),
    documents: parseLegislativeDocuments(documents),
    pipeline: parseLegislativePipeline(pipeline),
    questions: parseParliamentaryQuestions(questions),
  };
}
 
// ─── Breaking-News fetches ───────────────────────────────────────────────────
 
/**
 * Fetch voting anomaly text from MCP, returning empty string on failure.
 *
 * @param client - MCP client or null
 * @returns Raw anomaly data text
 */
export async function fetchVotingAnomalies(
  client: EuropeanParliamentMCPClient | null
): Promise<string> {
  if (!client) return '';
  try {
    const result = await callMCP(
      () => client.callTool('detect_voting_anomalies', { sensitivityThreshold: 0.3 }),
      undefined,
      'detect_voting_anomalies'
    );
    return result?.content?.[0]?.text ?? '';
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} detect_voting_anomalies failed:`, message);
    return '';
  }
}
 
/**
 * Fetch coalition dynamics analysis text from MCP.
 *
 * @param client - MCP client or null
 * @returns Raw coalition dynamics text
 */
export async function fetchCoalitionDynamics(
  client: EuropeanParliamentMCPClient | null
): Promise<string> {
  if (!client) return '';
  try {
    const result = await callMCP(
      () => client.callTool('analyze_coalition_dynamics', {}),
      undefined,
      'analyze_coalition_dynamics'
    );
    return result?.content?.[0]?.text ?? '';
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} analyze_coalition_dynamics failed:`, message);
    return '';
  }
}
 
/**
 * Fetch voting statistics report text from MCP.
 *
 * @param client - MCP client or null
 * @returns Raw voting report text
 */
export async function fetchVotingReport(
  client: EuropeanParliamentMCPClient | null
): Promise<string> {
  if (!client) return '';
  try {
    const result = await callMCP(
      () => client.callTool('generate_report', { reportType: 'VOTING_STATISTICS' }),
      undefined,
      'generate_report'
    );
    return result?.content?.[0]?.text ?? '';
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} generate_report failed:`, message);
    return '';
  }
}
 
/**
 * Fetch MEP influence assessment text from MCP.
 * Short-circuits immediately when `mepId` is empty.
 *
 * @param client - MCP client or null
 * @param mepId - MEP identifier; pass empty string to skip the call
 * @returns Raw influence data text
 */
export async function fetchMEPInfluence(
  client: EuropeanParliamentMCPClient | null,
  mepId: string
): Promise<string> {
  if (!mepId || !client) return '';
  try {
    const result = await callMCP(
      () => client.callTool('assess_mep_influence', { mepId, includeDetails: true }),
      undefined,
      'assess_mep_influence'
    );
    return result?.content?.[0]?.text ?? '';
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} assess_mep_influence failed:`, message);
    return '';
  }
}
 
// ─── Committee-Reports fetches ───────────────────────────────────────────────
 
/**
 * Load pre-fetched committee data for a given abbreviation from a JSON file.
 *
 * The file must be a JSON object keyed by committee abbreviation, where each
 * value conforms to {@link CommitteeData}.  This allows agentic workflows to
 * inject real EP committee data into the generator without a live MCP
 * connection (same pattern as {@link loadEPFeedDataFromFile}).
 *
 * @param filePath - Path to the JSON file
 * @param abbreviation - Committee code (e.g. `"ENVI"`)
 * @returns Parsed {@link CommitteeData} for the committee, or `undefined`
 */
export function loadCommitteeDataFromFile(
  filePath: string,
  abbreviation: string
): CommitteeData | undefined {
  try {
    if (!fs.existsSync(filePath)) {
      console.warn(`${WARN_PREFIX} Committee data file not found: ${filePath}`);
      return undefined;
    }
    const raw = fs.readFileSync(filePath, 'utf-8');
    const parsed: unknown = JSON.parse(raw);
    if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
      console.warn(`${WARN_PREFIX} Committee data file must contain a JSON object`);
      return undefined;
    }
    const obj = parsed as Record<string, unknown>;
    const entry = obj[abbreviation];
    if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
      return undefined;
    }
    const e = entry as Record<string, unknown>;
    const docs = Array.isArray(e['documents'])
      ? (e['documents'] as unknown[])
          .filter(
            (d): d is Record<string, unknown> =>
              typeof d === 'object' && d !== null && !Array.isArray(d)
          )
          .map((doc) => ({
            title: typeof doc['title'] === 'string' ? doc['title'] : 'Document',
            type: typeof doc['type'] === 'string' ? doc['type'] : 'Document',
            date: typeof doc['date'] === 'string' ? doc['date'] : '',
          }))
      : [];
    const result: CommitteeData = {
      name: typeof e['name'] === 'string' ? e['name'] : `${abbreviation} Committee`,
      abbreviation,
      chair: typeof e['chair'] === 'string' ? e['chair'] : 'N/A',
      members: typeof e['members'] === 'number' && Number.isFinite(e['members']) ? e['members'] : 0,
      documents: docs,
      effectiveness: typeof e['effectiveness'] === 'string' ? e['effectiveness'] : null,
    };
    console.log(
      `${INFO_PREFIX} Loaded committee data from file: ${result.name} (${docs.length} documents)`
    );
    return result;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} Failed to load committee data from file: ${message}`);
    return undefined;
  }
}
 
/**
 * Try to load committee data from the `EP_COMMITTEE_DATA_FILE` env var.
 * Returns the loaded {@link CommitteeData} when available, or `undefined` when
 * the env var is unset or the file does not contain an entry for the given
 * committee abbreviation.  Logs a warning when the file exists but the entry
 * is missing so callers can fall through to an MCP fetch.
 *
 * @param abbreviation - Committee code (e.g. `"ENVI"`)
 * @returns Pre-fetched committee data or `undefined`
 */
function tryLoadCommitteeDataFromEnv(abbreviation: string): CommitteeData | undefined {
  const filePath = process.env['EP_COMMITTEE_DATA_FILE'];
  if (!filePath) return undefined;
  const data = loadCommitteeDataFromFile(filePath, abbreviation);
  if (!data && fs.existsSync(filePath)) {
    console.warn(
      `${WARN_PREFIX} Committee data for ${abbreviation} not found in file — falling through to MCP fetch`
    );
  }
  return data;
}
 
/**
 * Fetch committee data from three MCP sources for the given abbreviation.
 * Each source failure is caught individually so partial data is still returned.
 *
 * When the environment variable `EP_COMMITTEE_DATA_FILE` is set, pre-fetched
 * committee data is loaded from that JSON file instead of calling the MCP
 * client.  This enables agentic workflows to inject real EP data.
 *
 * @param client - MCP client or null
 * @param abbreviation - Committee code (e.g. `"ENVI"`)
 * @returns Populated committee data
 */
export async function fetchCommitteeData(
  client: EuropeanParliamentMCPClient | null,
  abbreviation: string
): Promise<CommitteeData> {
  const defaultResult: CommitteeData = {
    name: `${abbreviation} Committee`,
    abbreviation,
    chair: 'N/A',
    members: 0,
    documents: [],
    effectiveness: null,
  };
 
  // Check for pre-fetched committee data file (set by EP_COMMITTEE_DATA_FILE env var).
  // This mirrors the EP_FEED_DATA_FILE pattern for fetchEPFeedData.
  const fromFile = tryLoadCommitteeDataFromEnv(abbreviation);
  if (fromFile) return fromFile;
 
  if (!client) return defaultResult;
 
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching committee info for ${abbreviation}...`);
    const committeeResult = await callMCP(
      () => client.getCommitteeInfo({ committeeId: abbreviation }),
      null,
      `getCommitteeInfo(${abbreviation})`
    );
    Iif (committeeResult) applyCommitteeInfo(committeeResult, defaultResult, abbreviation);
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    console.warn(`${WARN_PREFIX} getCommitteeInfo failed for ${abbreviation}:`, message);
  }
 
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching documents for ${abbreviation}...`);
    const docsResult = await callMCP(
      () => client.searchDocuments({ query: abbreviation, limit: 5 }),
      null,
      `searchDocuments(${abbreviation})`
    );
    Iif (docsResult) applyDocuments(docsResult, defaultResult);
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    console.warn(`${WARN_PREFIX} searchDocuments failed for ${abbreviation}:`, message);
  }
 
  try {
    const effectivenessResult = await callMCP(
      () =>
        client.analyzeLegislativeEffectiveness({
          subjectType: 'COMMITTEE',
          subjectId: abbreviation,
        }),
      null,
      `analyzeLegislativeEffectiveness(${abbreviation})`
    );
    if (effectivenessResult) applyEffectiveness(effectivenessResult, defaultResult);
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    console.warn(
      `${WARN_PREFIX} analyzeLegislativeEffectiveness failed for ${abbreviation}:`,
      message
    );
  }
 
  return defaultResult;
}
 
// ─── Motions fetches ─────────────────────────────────────────────────────────
 
/**
 * Fetch recent voting records from MCP.
 *
 * @param client - MCP client or null
 * @param dateFromStr - Start date (YYYY-MM-DD)
 * @param dateStr - End date (YYYY-MM-DD)
 * @returns Array of voting records
 */
export async function fetchVotingRecords(
  client: EuropeanParliamentMCPClient | null,
  dateFromStr: string,
  dateStr: string
): Promise<VotingRecord[]> {
  if (!client) return [];
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching voting records from MCP server...`);
    const votingResult = (await callMCP(
      () =>
        client.callTool('get_voting_records', {
          dateFrom: dateFromStr,
          dateTo: dateStr,
          limit: 20,
        }),
      undefined,
      'get_voting_records'
    )) as MCPToolResult | undefined;
 
    if (votingResult?.content?.[0]) {
      const data = parseJSON<{
        records?: Array<{
          title?: string | undefined;
          date?: string | undefined;
          result?: string | undefined;
          votes?:
            | {
                for?: number | undefined;
                against?: number | undefined;
                abstain?: number | undefined;
              }
            | undefined;
        }>;
      }>(votingResult.content[0].text, 'voting records');
 
      Eif (data?.records && data.records.length > 0) {
        console.log(`  ✅ Fetched ${data.records.length} voting records from MCP`);
        return data.records.map((r) => ({
          title: r.title ?? 'Parliamentary Vote',
          date: r.date ?? dateStr,
          result: r.result ?? 'Adopted',
          votes: {
            for: r.votes?.for ?? 0,
            against: r.votes?.against ?? 0,
            abstain: r.votes?.abstain ?? 0,
          },
        }));
      }
    }
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} MCP voting records fetch failed:`, message);
  }
  return [];
}
 
/**
 * Fetch voting patterns from MCP.
 *
 * @param client - MCP client or null
 * @param dateFromStr - Start date
 * @param dateStr - End date
 * @returns Array of voting patterns
 */
export async function fetchVotingPatterns(
  client: EuropeanParliamentMCPClient | null,
  dateFromStr: string,
  dateStr: string
): Promise<VotingPattern[]> {
  if (!client) return [];
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching voting patterns from MCP server...`);
    const patternsResult = (await callMCP(
      () =>
        client.callTool('analyze_voting_patterns', {
          dateFrom: dateFromStr,
          dateTo: dateStr,
        }),
      undefined,
      'analyze_voting_patterns'
    )) as MCPToolResult | undefined;
 
    if (patternsResult?.content?.[0]) {
      const data = parseJSON<{
        patterns?:
          | Array<{
              group?: string | undefined;
              cohesion?: number | undefined;
              participation?: number | undefined;
            }>
          | undefined;
      }>(patternsResult.content[0].text, 'voting patterns');
 
      Eif (data?.patterns && data.patterns.length > 0) {
        console.log(`  ✅ Fetched ${data.patterns.length} voting patterns from MCP`);
        return data.patterns.map((p) => ({
          group: p.group ?? 'Unknown Group',
          cohesion: p.cohesion ?? 0,
          participation: p.participation ?? 0,
        }));
      }
    }
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} MCP voting patterns fetch failed:`, message);
  }
  return [];
}
 
/**
 * Fetch voting anomalies for a date range from MCP.
 *
 * @param client - MCP client or null
 * @param dateFromStr - Start date
 * @param dateStr - End date
 * @returns Array of voting anomalies
 */
export async function fetchMotionsAnomalies(
  client: EuropeanParliamentMCPClient | null,
  dateFromStr: string,
  dateStr: string
): Promise<VotingAnomaly[]> {
  if (!client) return [];
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching voting anomalies from MCP server...`);
    const anomaliesResult = (await callMCP(
      () =>
        client.callTool('detect_voting_anomalies', {
          dateFrom: dateFromStr,
          dateTo: dateStr,
        }),
      undefined,
      'detect_voting_anomalies'
    )) as MCPToolResult | undefined;
 
    if (anomaliesResult?.content?.[0]) {
      const data = parseJSON<{
        anomalies?:
          | Array<{
              type?: string | undefined;
              description?: string | undefined;
              severity?: string | undefined;
            }>
          | undefined;
      }>(anomaliesResult.content[0].text, 'voting anomalies');
 
      Eif (data?.anomalies && data.anomalies.length > 0) {
        console.log(`  ✅ Fetched ${data.anomalies.length} voting anomalies from MCP`);
        return data.anomalies.map((a) => ({
          type: a.type ?? 'Unusual Pattern',
          description: a.description ?? 'No description available',
          severity: a.severity ?? 'MEDIUM',
        }));
      }
    }
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} MCP voting anomalies fetch failed:`, message);
  }
  return [];
}
 
/**
 * Fetch parliamentary questions from MCP for the given date range.
 *
 * @param client - MCP client or null
 * @param dateFromStr - Start date
 * @param dateStr - End date
 * @returns Array of parliamentary questions
 */
export async function fetchParliamentaryQuestionsForMotions(
  client: EuropeanParliamentMCPClient | null,
  dateFromStr: string,
  dateStr: string
): Promise<MotionsQuestion[]> {
  if (!client) return [];
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching parliamentary questions from MCP server...`);
    const questionsResult = await callMCP(
      () =>
        client.getParliamentaryQuestions({
          dateFrom: dateFromStr,
          dateTo: dateStr,
          limit: 10,
        }),
      undefined,
      'get_parliamentary_questions'
    );
 
    if (questionsResult?.content?.[0]) {
      const data = parseJSON<{
        questions?: Array<{
          author?: string | undefined;
          topic?: string | undefined;
          subject?: string | undefined;
          date?: string | undefined;
          status?: string | undefined;
        }>;
      }>(questionsResult.content[0].text, 'parliamentary questions');
 
      if (data?.questions && data.questions.length > 0) {
        console.log(`  ✅ Fetched ${data.questions.length} parliamentary questions from MCP`);
        return data.questions.map((q) => ({
          author: q.author ?? 'Unknown MEP',
          topic: q.topic ?? q.subject ?? 'General inquiry',
          date: q.date ?? dateStr,
          status: q.status ?? 'PENDING',
        }));
      }
    }
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} MCP parliamentary questions fetch failed:`, message);
  }
  return [];
}
 
/**
 * Fetch all motions data in parallel, applying fallback arrays for any
 * section where MCP returned nothing.
 *
 * @param client - MCP client or null
 * @param dateFromStr - Start date
 * @param dateStr - End date
 * @returns All motions data with fallbacks applied
 */
export async function fetchMotionsData(
  client: EuropeanParliamentMCPClient | null,
  dateFromStr: string,
  dateStr: string
): Promise<{
  votingRecords: VotingRecord[];
  votingPatterns: VotingPattern[];
  anomalies: VotingAnomaly[];
  questions: MotionsQuestion[];
}> {
  const [votingRecordsResult, votingPatternsResult, anomaliesResult, questionsResult] =
    await Promise.allSettled([
      fetchVotingRecords(client, dateFromStr, dateStr),
      fetchVotingPatterns(client, dateFromStr, dateStr),
      fetchMotionsAnomalies(client, dateFromStr, dateStr),
      fetchParliamentaryQuestionsForMotions(client, dateFromStr, dateStr),
    ]);
 
  let votingRecords: VotingRecord[] =
    votingRecordsResult.status === 'fulfilled' ? votingRecordsResult.value : [];
  Iif (votingRecordsResult.status === 'rejected') {
    console.warn(`${WARN_PREFIX} Failed to fetch voting records from MCP`);
  }
 
  let votingPatterns: VotingPattern[] =
    votingPatternsResult.status === 'fulfilled' ? votingPatternsResult.value : [];
  Iif (votingPatternsResult.status === 'rejected') {
    console.warn(`${WARN_PREFIX} Failed to fetch voting patterns from MCP`);
  }
 
  let anomalies: VotingAnomaly[] =
    anomaliesResult.status === 'fulfilled' ? anomaliesResult.value : [];
  Iif (anomaliesResult.status === 'rejected') {
    console.warn(`${WARN_PREFIX} Failed to fetch voting anomalies from MCP`);
  }
 
  let questions: MotionsQuestion[] =
    questionsResult.status === 'fulfilled' ? questionsResult.value : [];
  Iif (questionsResult.status === 'rejected') {
    console.warn(`${WARN_PREFIX} Failed to fetch parliamentary questions from MCP`);
  }
 
  const fallback = getMotionsFallbackData(dateStr, dateFromStr);
 
  if (votingRecords.length === 0) {
    console.log(`${INFO_PREFIX} Using placeholder voting records`);
    votingRecords = fallback.votingRecords;
  }
  if (votingPatterns.length === 0) {
    console.log(`${INFO_PREFIX} Using placeholder voting patterns`);
    votingPatterns = fallback.votingPatterns;
  }
  if (anomalies.length === 0) {
    console.log(`${INFO_PREFIX} Using placeholder voting anomalies`);
    anomalies = fallback.anomalies;
  }
  Eif (questions.length === 0) {
    console.log(`${INFO_PREFIX} Using placeholder parliamentary questions`);
    questions = fallback.questions;
  }
 
  return { votingRecords, votingPatterns, anomalies, questions };
}
 
// ─── Propositions fetches ─────────────────────────────────────────────────────
 
/**
 * Fetch legislative proposals from MCP and build pre-sanitised HTML.
 *
 * @param client - MCP client or null
 * @returns Proposals HTML and the first procedure ID found (if any)
 */
export async function fetchProposalsFromMCP(
  client: EuropeanParliamentMCPClient | null
): Promise<{ html: string; firstProcedureId: string }> {
  if (!client) return { html: '', firstProcedureId: '' };
 
  const docsResult = await callMCP(
    () => client.searchDocuments({ keyword: 'legislative proposal', limit: 10 }),
    undefined,
    'search_documents(proposals)'
  );
  if (!docsResult?.content?.[0]) return { html: '', firstProcedureId: '' };
 
  const data = parseJSON<{ documents?: Array<Partial<LegislativeDocument>> }>(
    docsResult.content[0].text,
    'proposals'
  );
  if (!data?.documents?.length) return { html: '', firstProcedureId: '' };
 
  console.log(`  ✅ Fetched ${data.documents.length} proposals from MCP`);
 
  const firstProcedureId =
    data.documents.find((d) => /\d{4}\/\d+\(.+\)/.test(d.id ?? ''))?.id ?? '';
 
  const html = data.documents
    .map(
      (doc) => `
      <div class="proposal-card">
        <h3>${escapeHTML(doc.title ?? 'Legislative Proposal')}</h3>
        <div class="proposal-meta">
          ${doc.id ? `<span class="proposal-id">${escapeHTML(doc.id)}</span>` : ''}
          ${doc.date ? `<span class="proposal-date">${escapeHTML(doc.date)}</span>` : ''}
          ${doc.status ? `<span class="proposal-status">${escapeHTML(doc.status)}</span>` : ''}
        </div>
        ${doc.committee ? `<p class="proposal-committee">${escapeHTML(doc.committee)}</p>` : ''}
        ${doc.rapporteur ? `<p class="proposal-rapporteur">${escapeHTML(doc.rapporteur)}</p>` : ''}
      </div>`
    )
    .join('');
 
  return { html, firstProcedureId };
}
 
/**
 * Fetch active legislative pipeline data from MCP.
 *
 * @param client - MCP client or null
 * @returns Structured pipeline data or null when unavailable
 */
export async function fetchPipelineFromMCP(
  client: EuropeanParliamentMCPClient | null
): Promise<PipelineData | null> {
  if (!client) return null;
 
  const pipelineResult = await callMCP(
    () => client.monitorLegislativePipeline({ status: 'ACTIVE', limit: 5 }),
    undefined,
    'monitor_legislative_pipeline'
  );
  if (!pipelineResult?.content?.[0]) return null;
 
  const pipeData = parseJSON<{
    pipelineHealthScore?: number | undefined;
    throughputRate?: number | undefined;
    procedures?:
      | Array<{
          id?: string | undefined;
          title?: string | undefined;
          stage?: string | undefined;
        }>
      | undefined;
  }>(pipelineResult.content[0].text, 'pipeline');
 
  if (!pipeData) return null;
 
  const healthScore = pipeData.pipelineHealthScore ?? 0;
  const throughput = pipeData.throughputRate ?? 0;
  const procRowsHtml =
    pipeData.procedures
      ?.map(
        (proc) => `
      <div class="procedure-item">
        ${proc.id ? `<span class="procedure-id">${escapeHTML(proc.id)}</span>` : ''}
        ${proc.title ? `<span class="procedure-title">${escapeHTML(proc.title)}</span>` : ''}
        ${proc.stage ? `<span class="procedure-stage">${escapeHTML(proc.stage)}</span>` : ''}
      </div>`
      )
      .join('') ?? '';
 
  return { healthScore, throughput, procRowsHtml };
}
 
/**
 * Fetch a specific procedure's tracked-status HTML from MCP.
 * Returns empty string when `procedureId` is empty or MCP is unavailable.
 *
 * @param client - MCP client or null
 * @param procedureId - Procedure ID (e.g. `"2024/0001(COD)"`)
 * @returns HTML snippet for the procedure status section
 */
export async function fetchProcedureStatusFromMCP(
  client: EuropeanParliamentMCPClient | null,
  procedureId: string
): Promise<string> {
  if (!procedureId || !client) return '';
  try {
    const result = await callMCP(
      () => client.trackLegislation(procedureId),
      undefined,
      `track_legislation(${procedureId})`
    );
    if (!result?.content?.[0]) return '';
    const raw = result.content[0].text;
    return `<pre class="data-summary">${escapeHTML(raw.slice(0, 2000))}</pre>`;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} track_legislation failed:`, message);
    return '';
  }
}
 
// ─── EP Feed-based fetches (Breaking News) ──────────────────────────────────
 
/**
 * Parse a feed result from MCP into a flat array of items.
 * EP API v2 feeds return items under the `data` key:
 * `{ data: [{ id, type, work_type, identifier, label }], "@context": [...] }`
 *
 * Also handles legacy shapes (`feed`, `entries`, `items`) and bare arrays.
 *
 * @param result - Raw MCP tool result
 * @returns Array of parsed feed entry objects (may be empty)
 */
function parseFeedResult(result: MCPToolResult | undefined): Record<string, unknown>[] {
  if (!result?.content?.[0]?.text) return [];
  const parsed = parseJSON<unknown>(result.content[0].text, 'feed');
  if (!parsed) return [];
  // EP API v2 feeds use `data` key; also check legacy shapes
  const candidates = [
    (parsed as Record<string, unknown>)['data'],
    (parsed as Record<string, unknown>)['feed'],
    (parsed as Record<string, unknown>)['entries'],
    (parsed as Record<string, unknown>)['items'],
    parsed,
  ];
  for (const candidate of candidates) {
    if (Array.isArray(candidate)) return candidate as Record<string, unknown>[];
  }
  return [];
}
 
/**
 * Parse an EP API v2 feed response envelope in a single JSON parse, returning
 * both the array of feed items and the API-reported total count.
 * Avoids parsing the same JSON payload twice when both values are needed.
 *
 * @param result - Raw MCP tool result
 * @returns Object with `items` array and `total` count from the API
 */
function parseFeedEnvelope(result: MCPToolResult | undefined): {
  items: Record<string, unknown>[];
  total: number;
} {
  if (!result?.content?.[0]?.text) return { items: [], total: 0 };
  const parsed = parseJSON<unknown>(result.content[0].text, 'feed');
  Iif (!parsed || typeof parsed !== 'object') return { items: [], total: 0 };
  const envelope = parsed as Record<string, unknown>;
  const total = typeof envelope['total'] === 'number' ? envelope['total'] : 0;
  const candidates = [
    envelope['data'],
    envelope['feed'],
    envelope['entries'],
    envelope['items'],
    parsed,
  ];
  for (const candidate of candidates) {
    if (Array.isArray(candidate)) return { items: candidate as Record<string, unknown>[], total };
  }
  return { items: [], total };
}
 
/**
 * Map a raw EP API v2 feed item to a normalized feed item.
 * EP feeds return `{ id, type, work_type, identifier, label }` — we normalize
 * these into the domain feed item shape, using `label` as `title` when no title exists.
 *
 * @param item - Raw feed item record
 * @returns Common feed item fields
 */
function mapFeedItemBase(item: Record<string, unknown>): {
  id: string;
  title: string;
  date: string;
  type?: string | undefined;
  url?: string | undefined;
  identifier?: string | undefined;
  label?: string | undefined;
} {
  return {
    id: String(item['id'] ?? item['docId'] ?? ''),
    title: String(
      item['title'] ?? item['label'] ?? item['name'] ?? item['identifier'] ?? 'Untitled'
    ),
    date: String(item['date'] ?? item['published'] ?? item['updated'] ?? ''),
    type: item['type']
      ? String(item['type'])
      : item['work_type']
        ? String(item['work_type'])
        : undefined,
    url: item['url'] ? String(item['url']) : undefined,
    identifier: item['identifier'] ? String(item['identifier']) : undefined,
    label: item['label'] ? String(item['label']) : undefined,
  };
}
 
/**
 * Fetch adopted texts feed from MCP.
 *
 * @param client - MCP client or null
 * @param timeframe - How far back to look (default: 'one-day')
 * @returns Array of adopted text feed items
 */
export async function fetchAdoptedTextsFeed(
  client: EuropeanParliamentMCPClient | null,
  timeframe: FeedTimeframe = 'one-day'
): Promise<AdoptedTextFeedItem[]> {
  if (!client) return [];
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching adopted texts feed (${timeframe})...`);
    const result = await callMCP(
      () => client.getAdoptedTextsFeed({ timeframe, limit: 20 }),
      undefined,
      'get_adopted_texts_feed'
    );
    return parseFeedResult(result).map((item) => mapFeedItemBase(item));
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} get_adopted_texts_feed failed:`, message);
    return [];
  }
}
 
/**
 * Fetch events feed from MCP.
 *
 * @param client - MCP client or null
 * @param timeframe - How far back to look (default: 'one-day')
 * @returns Array of event feed items
 */
export async function fetchEventsFeed(
  client: EuropeanParliamentMCPClient | null,
  timeframe: FeedTimeframe = 'one-day'
): Promise<EventFeedItem[]> {
  if (!client) return [];
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching events feed (${timeframe})...`);
    const result = await callMCP(
      () => client.getEventsFeed({ timeframe, limit: 20 }),
      undefined,
      'get_events_feed'
    );
    return parseFeedResult(result).map((item) => ({
      ...mapFeedItemBase(item),
      location: item['location'] ? String(item['location']) : undefined,
    }));
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} get_events_feed failed:`, message);
    return [];
  }
}
 
/**
 * Fetch procedures feed from MCP.
 *
 * @param client - MCP client or null
 * @param timeframe - How far back to look (default: 'one-day')
 * @returns Array of procedure feed items
 */
export async function fetchProceduresFeed(
  client: EuropeanParliamentMCPClient | null,
  timeframe: FeedTimeframe = 'one-day'
): Promise<ProcedureFeedItem[]> {
  if (!client) return [];
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching procedures feed (${timeframe})...`);
    const result = await callMCP(
      () => client.getProceduresFeed({ timeframe, limit: 20 }),
      undefined,
      'get_procedures_feed'
    );
    return parseFeedResult(result).map((item) => ({
      ...mapFeedItemBase(item),
      stage: item['stage'] ? String(item['stage']) : undefined,
    }));
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} get_procedures_feed failed:`, message);
    return [];
  }
}
 
/**
 * Fetch MEPs feed from MCP.
 *
 * @param client - MCP client or null
 * @param timeframe - How far back to look (default: 'one-day')
 * @returns Array of MEP feed items
 */
export async function fetchMEPsFeed(
  client: EuropeanParliamentMCPClient | null,
  timeframe: FeedTimeframe = 'one-day'
): Promise<MEPFeedItem[]> {
  return (await fetchMEPsFeedWithTotal(client, timeframe)).items;
}
 
/**
 * Fetch MEPs feed from MCP, returning both items and the API's reported total count.
 * The `total` from the API response reflects all matching records in the feed,
 * which may exceed the `limit` parameter (currently capped at 100 per request).
 *
 * The limit is set to 100 (the EP API maximum) so the fetched sample is large
 * enough to populate a meaningful truncation note ("showing 10 of N") while
 * keeping each request bounded.  When the feed contains more than 100 MEP
 * updates, the `total` field in the API response carries the true count.
 *
 * @param client - MCP client or null
 * @param timeframe - How far back to look (default: 'one-day')
 * @returns Object with `items` array and `total` count from the API
 */
export async function fetchMEPsFeedWithTotal(
  client: EuropeanParliamentMCPClient | null,
  timeframe: FeedTimeframe = 'one-day'
): Promise<{ items: MEPFeedItem[]; total: number }> {
  if (!client) return { items: [], total: 0 };
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching MEPs feed (${timeframe})...`);
    const result = await callMCP(
      () => client.getMEPsFeed({ timeframe, limit: 100 }),
      undefined,
      'get_meps_feed'
    );
    const { items: rawItems, total } = parseFeedEnvelope(result);
    const items = rawItems.map((item) => ({
      id: String(item['id'] ?? item['mepId'] ?? ''),
      name: String(item['name'] ?? item['label'] ?? item['title'] ?? 'Unknown'),
      date: String(item['date'] ?? item['published'] ?? item['updated'] ?? ''),
      country: item['country'] ? String(item['country']) : undefined,
      group: item['group'] ? String(item['group']) : undefined,
      url: item['url'] ? String(item['url']) : undefined,
      identifier: item['identifier'] ? String(item['identifier']) : undefined,
      label: item['label'] ? String(item['label']) : undefined,
    }));
    return { items, total };
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} get_meps_feed failed:`, message);
    return { items: [], total: 0 };
  }
}
 
/**
 * Fetch documents feed from MCP.
 *
 * @param client - MCP client or null
 * @param timeframe - How far back to look (default: 'one-day')
 * @returns Array of document feed items
 */
export async function fetchDocumentsFeed(
  client: EuropeanParliamentMCPClient | null,
  timeframe: FeedTimeframe = 'one-day'
): Promise<DocumentFeedItem[]> {
  Eif (!client) return [];
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching documents feed (${timeframe})...`);
    const result = await callMCP(
      () => client.getDocumentsFeed({ timeframe, limit: 20 }),
      undefined,
      'get_documents_feed'
    );
    return parseFeedResult(result).map((item) => mapFeedItemBase(item));
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} get_documents_feed failed:`, message);
    return [];
  }
}
 
/**
 * Fetch plenary documents feed from MCP.
 *
 * @param client - MCP client or null
 * @param timeframe - How far back to look (default: 'one-day')
 * @returns Array of document feed items
 */
export async function fetchPlenaryDocumentsFeed(
  client: EuropeanParliamentMCPClient | null,
  timeframe: FeedTimeframe = 'one-day'
): Promise<DocumentFeedItem[]> {
  Eif (!client) return [];
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching plenary documents feed (${timeframe})...`);
    const result = await callMCP(
      () => client.getPlenaryDocumentsFeed({ timeframe, limit: 20 }),
      undefined,
      'get_plenary_documents_feed'
    );
    return parseFeedResult(result).map((item) => mapFeedItemBase(item));
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} get_plenary_documents_feed failed:`, message);
    return [];
  }
}
 
/**
 * Fetch committee documents feed from MCP.
 *
 * @param client - MCP client or null
 * @param timeframe - How far back to look (default: 'one-day')
 * @returns Array of document feed items
 */
export async function fetchCommitteeDocumentsFeed(
  client: EuropeanParliamentMCPClient | null,
  timeframe: FeedTimeframe = 'one-day'
): Promise<DocumentFeedItem[]> {
  Eif (!client) return [];
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching committee documents feed (${timeframe})...`);
    const result = await callMCP(
      () => client.getCommitteeDocumentsFeed({ timeframe, limit: 20 }),
      undefined,
      'get_committee_documents_feed'
    );
    return parseFeedResult(result).map((item) => mapFeedItemBase(item));
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} get_committee_documents_feed failed:`, message);
    return [];
  }
}
 
/**
 * Fetch plenary session documents feed from MCP.
 *
 * @param client - MCP client or null
 * @param timeframe - How far back to look (default: 'one-day')
 * @returns Array of document feed items
 */
export async function fetchPlenarySessionDocumentsFeed(
  client: EuropeanParliamentMCPClient | null,
  timeframe: FeedTimeframe = 'one-day'
): Promise<DocumentFeedItem[]> {
  Eif (!client) return [];
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching plenary session documents feed (${timeframe})...`);
    const result = await callMCP(
      () => client.getPlenarySessionDocumentsFeed({ timeframe, limit: 20 }),
      undefined,
      'get_plenary_session_documents_feed'
    );
    return parseFeedResult(result).map((item) => mapFeedItemBase(item));
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} get_plenary_session_documents_feed failed:`, message);
    return [];
  }
}
 
/**
 * Fetch external documents feed from MCP.
 *
 * @param client - MCP client or null
 * @param timeframe - How far back to look (default: 'one-day')
 * @returns Array of document feed items
 */
export async function fetchExternalDocumentsFeed(
  client: EuropeanParliamentMCPClient | null,
  timeframe: FeedTimeframe = 'one-day'
): Promise<DocumentFeedItem[]> {
  Eif (!client) return [];
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching external documents feed (${timeframe})...`);
    const result = await callMCP(
      () => client.getExternalDocumentsFeed({ timeframe, limit: 20 }),
      undefined,
      'get_external_documents_feed'
    );
    return parseFeedResult(result).map((item) => mapFeedItemBase(item));
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} get_external_documents_feed failed:`, message);
    return [];
  }
}
 
/**
 * Fetch parliamentary questions feed from MCP.
 *
 * @param client - MCP client or null
 * @param timeframe - How far back to look (default: 'one-day')
 * @returns Array of question feed items
 */
export async function fetchQuestionsFeed(
  client: EuropeanParliamentMCPClient | null,
  timeframe: FeedTimeframe = 'one-day'
): Promise<QuestionFeedItem[]> {
  Eif (!client) return [];
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching parliamentary questions feed (${timeframe})...`);
    const result = await callMCP(
      () => client.getParliamentaryQuestionsFeed({ timeframe, limit: 20 }),
      undefined,
      'get_parliamentary_questions_feed'
    );
    return parseFeedResult(result).map((item) => mapFeedItemBase(item));
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} get_parliamentary_questions_feed failed:`, message);
    return [];
  }
}
 
/**
 * Fetch MEP declarations feed from MCP.
 *
 * @param client - MCP client or null
 * @param timeframe - How far back to look (default: 'one-day')
 * @returns Array of declaration feed items
 */
export async function fetchDeclarationsFeed(
  client: EuropeanParliamentMCPClient | null,
  timeframe: FeedTimeframe = 'one-day'
): Promise<DeclarationFeedItem[]> {
  Eif (!client) return [];
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching MEP declarations feed (${timeframe})...`);
    const result = await callMCP(
      () => client.getMEPDeclarationsFeed({ timeframe, limit: 20 }),
      undefined,
      'get_mep_declarations_feed'
    );
    return parseFeedResult(result).map((item) => mapFeedItemBase(item));
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} get_mep_declarations_feed failed:`, message);
    return [];
  }
}
 
/**
 * Fetch corporate bodies feed from MCP.
 *
 * @param client - MCP client or null
 * @param timeframe - How far back to look (default: 'one-day')
 * @returns Array of corporate body feed items
 */
export async function fetchCorporateBodiesFeed(
  client: EuropeanParliamentMCPClient | null,
  timeframe: FeedTimeframe = 'one-day'
): Promise<CorporateBodyFeedItem[]> {
  Eif (!client) return [];
  try {
    console.log(`${MCP_FETCH_PREFIX} Fetching corporate bodies feed (${timeframe})...`);
    const result = await callMCP(
      () => client.getCorporateBodiesFeed({ timeframe, limit: 20 }),
      undefined,
      'get_corporate_bodies_feed'
    );
    return parseFeedResult(result).map((item) => mapFeedItemBase(item));
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn(`${WARN_PREFIX} get_corporate_bodies_feed failed:`, message);
    return [];
  }
}
 
/**
 * Fetch all EP feed data for breaking news articles.
 * Calls adopted texts, events, procedures, and MEPs feeds in parallel.
 * Returns `undefined` when client is null (MCP unavailable).
 *
 * @param client - MCP client or null
 * @param timeframe - How far back to look (default: 'one-day')
 * @returns Aggregated feed data for breaking news, or undefined when client is null
 */
export async function fetchBreakingNewsFeedData(
  client: EuropeanParliamentMCPClient | null,
  timeframe: FeedTimeframe = 'one-day'
): Promise<BreakingNewsFeedData | undefined> {
  if (!client) return undefined;
  if (!mcpCircuitBreaker.canRequest()) {
    console.warn(
      `${WARN_PREFIX} Circuit breaker OPEN — treating as MCP unavailable for breaking news feeds`
    );
    return undefined;
  }
  const [adoptedTexts, events, procedures, mepFeedResult] = await Promise.all([
    fetchAdoptedTextsFeed(client, timeframe),
    fetchEventsFeed(client, timeframe),
    fetchProceduresFeed(client, timeframe),
    fetchMEPsFeedWithTotal(client, timeframe),
  ]);
  const { items: mepUpdates, total: totalMEPUpdates } = mepFeedResult;
  return {
    adoptedTexts,
    events,
    procedures,
    mepUpdates,
    totalMEPUpdates: totalMEPUpdates > 0 ? totalMEPUpdates : undefined,
  };
}
 
/**
 * Fetch comprehensive EP feed data from all 12 feed endpoints in parallel.
 * This is the primary data source for all article strategies.
 *
 * @param client - MCP client or null
 * @param timeframe - How far back to look (default: 'one-day')
 * @param dateRange - Optional inclusive UTC window for filtering feed items
 * @returns Full EPFeedData or undefined when client is null
 */
export async function fetchEPFeedData(
  client: EuropeanParliamentMCPClient | null,
  timeframe: FeedTimeframe = 'one-day',
  dateRange?: DateRange
): Promise<EPFeedData | undefined> {
  // Check for pre-fetched feed data file (set by --feed-data CLI arg).
  // This allows agentic workflows to pass MCP data fetched via framework tools
  // into the generator without requiring a direct MCP connection.
  const feedDataFile = process.env['EP_FEED_DATA_FILE'];
  if (feedDataFile) {
    const fileData = loadEPFeedDataFromFile(feedDataFile, dateRange);
    if (fileData) return fileData;
    console.log(
      `${WARN_PREFIX} Pre-fetched EP feed data failed to load — falling through to MCP fetch`
    );
  }
  if (!client) return undefined;
  Eif (!mcpCircuitBreaker.canRequest()) {
    console.warn(`${WARN_PREFIX} Circuit breaker OPEN — treating as MCP unavailable for EP feeds`);
    return undefined;
  }
  console.log(`${MCP_FETCH_PREFIX} Fetching comprehensive EP feed data (${timeframe})...`);
  const [
    adoptedTexts,
    events,
    procedures,
    mepUpdates,
    documents,
    plenaryDocuments,
    committeeDocuments,
    plenarySessionDocuments,
    externalDocuments,
    questions,
    declarations,
    corporateBodies,
  ] = await Promise.all([
    fetchAdoptedTextsFeed(client, timeframe),
    fetchEventsFeed(client, timeframe),
    fetchProceduresFeed(client, timeframe),
    fetchMEPsFeed(client, timeframe),
    fetchDocumentsFeed(client, timeframe),
    fetchPlenaryDocumentsFeed(client, timeframe),
    fetchCommitteeDocumentsFeed(client, timeframe),
    fetchPlenarySessionDocumentsFeed(client, timeframe),
    fetchExternalDocumentsFeed(client, timeframe),
    fetchQuestionsFeed(client, timeframe),
    fetchDeclarationsFeed(client, timeframe),
    fetchCorporateBodiesFeed(client, timeframe),
  ]);
 
  const filteredData = filterEPFeedDataByDateRange(
    {
      adoptedTexts,
      events,
      procedures,
      mepUpdates,
      documents,
      plenaryDocuments,
      committeeDocuments,
      plenarySessionDocuments,
      externalDocuments,
      questions,
      declarations,
      corporateBodies,
    },
    dateRange
  );
  const totalItems =
    filteredData.adoptedTexts.length +
    filteredData.events.length +
    filteredData.procedures.length +
    filteredData.mepUpdates.length +
    filteredData.documents.length +
    filteredData.plenaryDocuments.length +
    filteredData.committeeDocuments.length +
    filteredData.plenarySessionDocuments.length +
    filteredData.externalDocuments.length +
    filteredData.questions.length +
    filteredData.declarations.length +
    filteredData.corporateBodies.length;
  console.log(`  ✅ Fetched ${totalItems} total feed items across 12 endpoints`);
 
  return filteredData;
}