All files / shared/utils/src/api-clients tavus-client.ts

0% Statements 0/832
0% Branches 0/581
0% Functions 0/93
0% Lines 0/820

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 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * Tavus.io API Client for video avatar generation and streaming
 * 
 * This client handles authentication, video avatar generation, and streaming
 * capabilities using the Tavus.io API. It supports multiple pipeline modes
 * and integrates with Raven-0 for page awareness and perception analysis.
 * 
 * For prototype/local development, API keys are stored insecurely.
 * In production, this should be changed to use secure key management.
 */
 
// Test API key for development - DO NOT USE IN PRODUCTION
import { getTavusApiKey } from '@buzztrail/tavus-client';
const TEST_TAVUS_API_KEY = getTavusApiKey();
 
import type { UserPreferences } from '@buzztrail/shared-types';
import type { TavusConversationObject } from '@buzztrail/tavus-types';
import { getTavusLogger } from './tavus-logger-browser';
import { logger as appLogger } from '../logger';
 
// Cost tracking for development
let costTrackingEnabled = false;
let costTrackingCallback: ((callType: string) => boolean) | null = null;
 
/**
 * Enable cost tracking for development
 */
export function enableCostTracking(callback: (callType: string) => boolean): void {
  costTrackingEnabled = true;
  costTrackingCallback = callback;
}
 
/**
 * Disable cost tracking
 */
export function disableCostTracking(): void {
  costTrackingEnabled = false;
  costTrackingCallback = null;
}
 
// WebRTC video streaming implementation
 
/**
 * Pipeline modes supported by Tavus.io API
 */
export type TavusPipelineMode = 'basic' | 'enhanced' | 'premium' | 'enterprise';
 
/**
 * Replica status from Tavus API
 */
export type ReplicaStatus = 'training' | 'completed' | 'failed' | 'pending';
 
/**
 * Configuration for TavusClient initialization
 */
export interface TavusConfig {
  /** API key for Tavus.io authentication (optional - will use test key if not provided) */
  apiKey?: string;
  /** Base URL for Tavus API (defaults to v2) */
  baseUrl?: string;
  /** Default pipeline mode */
  defaultPipelineMode?: TavusPipelineMode;
  /** User preferences for video settings */
  userPreferences?: UserPreferences;
  /** Whether to enable debug logging */
  debug?: boolean;
}
 
/**
 * Replica information from Tavus API
 */
export interface TavusReplica {
  /** Unique identifier for the replica */
  replicaId: string;
  /** Human-readable name for the replica */
  replicaName: string;
  /** Type of replica (e.g., 'user', 'system') */
  replicaType: string;
  /** Current status of the replica */
  status: ReplicaStatus;
  /** Training progress (e.g., "100/100") */
  trainingProgress?: string;
  /** URL to thumbnail video */
  thumbnailVideoUrl?: string;
  /** Timestamp when replica was created */
  createdAt: string;
  /** Timestamp when replica was last updated */
  updatedAt: string;
  /** Error message if status is 'failed' */
  errorMessage?: string;
}
 
/**
 * Page analysis result from Raven-0 integration
 */
export interface PageAnalysis {
  /** Extracted page title */
  title: string;
  /** Page description or summary */
  description: string;
  /** List of interactive elements found */
  interactiveElements: InteractiveElement[];
  /** Navigation opportunities within the site */
  navigationOptions: NavigationOption[];
  /** Content summary for AI context */
  contentSummary: string;
  /** User intent analysis */
  userIntent: string;
  /** Page type classification */
  pageType: 'e-commerce' | 'help-desk' | 'blog' | 'saas' | 'other';
}
 
/**
 * Interactive element found on the page
 */
export interface InteractiveElement {
  /** Element type (button, form, link, etc.) */
  type: string;
  /** Element text or label */
  text: string;
  /** Element's href or action */
  action?: string;
  /** Element's position on page */
  position: {
    x: number;
    y: number;
  };
  /** Whether element is currently visible */
  visible: boolean;
}
 
/**
 * Navigation option within the same site
 */
export interface NavigationOption {
  /** URL to navigate to */
  url: string;
  /** Link text or description */
  text: string;
  /** Whether this is a primary navigation option */
  primary: boolean;
}
 
/**
 * Perception analysis result from Raven-0
 */
export interface PerceptionAnalysis {
  /** Overall page sentiment */
  sentiment: 'positive' | 'negative' | 'neutral';
  /** User engagement level */
  engagementLevel: 'low' | 'medium' | 'high';
  /** Recommended AI behavior */
  recommendedBehavior: string;
  /** Contextual insights */
  insights: string[];
  /** Confidence score (0-1) */
  confidence: number;
}
 
/**
 * Message context for sending to Tavus API
 */
export interface MessageContext {
  /** Current page URL */
  pageUrl: string;
  /** Page title */
  pageTitle: string;
  /** Page analysis results */
  pageAnalysis?: PageAnalysis;
  /** User's current persona */
  persona?: string;
  /** Pipeline mode to use */
  pipelineMode?: TavusPipelineMode;
}
 
/**
 * Response from Tavus API
 */
export interface TavusResponse {
  /** Success status */
  success: boolean;
  /** Response data */
  data?: Record<string, unknown>;
  /** Error message if failed */
  error?: string;
  /** HTTP status code */
  statusCode?: number;
}
 
/**
 * Error types for TavusClient
 */
export type TavusErrorType = 
  | 'authentication'
  | 'network'
  | 'rate_limit'
  | 'validation'
  | 'server'
  | 'timeout'
  | 'unknown';
 
/**
 * Enhanced error information
 */
export interface TavusError {
  /** Error type for categorization */
  type: TavusErrorType;
  /** Human-readable error message */
  message: string;
  /** Original error object */
  originalError?: Error;
  /** HTTP status code if applicable */
  statusCode?: number;
  /** Retry information */
  retryable: boolean;
  /** Suggested retry delay in milliseconds */
  retryDelay?: number;
  /** Context information */
  context?: Record<string, unknown>;
}
 
/**
 * Retry configuration for API calls
 */
export interface RetryConfig {
  /** Maximum number of retry attempts */
  maxRetries: number;
  /** Base delay between retries in milliseconds */
  baseDelay: number;
  /** Maximum delay between retries in milliseconds */
  maxDelay: number;
  /** Whether to use exponential backoff */
  exponentialBackoff: boolean;
  /** HTTP status codes that should trigger retries */
  retryStatusCodes: number[];
}
 
/**
 * Video visibility state
 */
export interface VideoVisibilityState {
  /** Whether user video is currently visible */
  isVisible: boolean;
  /** Last time visibility was changed */
  lastChanged: Date;
  /** User who changed the visibility */
  changedBy?: string;
  /** Reason for the change */
  reason?: string;
}
 
/**
 * Tavus session for video avatar generation
 */
export interface TavusSession {
  /** Unique session identifier */
  sessionId: string;
  /** Replica ID to use for this session */
  replicaId: string;
  /** Persona ID for behavior configuration */
  personaId: string;
  /** WebRTC room URL for real-time streaming */
  webRtcRoomUrl: string;
  /** Current session status */
  status: 'pending' | 'active' | 'ended' | 'error';
  /** URL to session transcript */
  transcriptUrl?: string;
  /** URL to session recording */
  recordingUrl?: string;
  /** Session start timestamp */
  startedAt: string;
  /** Session end timestamp */
  endedAt?: string;
  /** Error message if status is 'error' */
  error?: string;
}
 
/**
 * Configuration for Replica models
 */
export interface ReplicaConfig {
  /** Unique replica identifier */
  replicaId: string;
  /** Human-readable display name */
  displayName: string;
  /** URL to avatar preview image */
  avatarUrl: string;
  /** Model type (Replica or Phoenix) */
  modelType: 'Replica' | 'Phoenix';
  /** Creation timestamp */
  createdAt: string;
  /** Last update timestamp */
  updatedAt?: string;
  /** Training progress (0-100) */
  trainingProgress?: number;
  /** Whether replica is ready for use */
  isReady: boolean;
}
 
/**
 * Configuration for Persona settings
 */
export interface PersonaConfig {
  /** Unique persona identifier */
  personaId: string;
  /** Human-readable name */
  name: string;
  /** Description of persona behavior */
  description: string;
  /** Prompt template for persona */
  promptTemplate: string;
  /** Language code (ISO 639-1) */
  language: string;
  /** Voice engine to use */
  voiceEngine: string;
  /** Pipeline mode for this persona */
  pipelineMode: TavusPipelineMode;
}
 
/**
 * Video streaming session information
 */
export interface VideoStreamSession {
  /** Session ID */
  sessionId: string;
  /** WebRTC room URL */
  roomUrl: string;
  /** Room access token */
  accessToken: string;
  /** Whether session is active */
  isActive: boolean;
  /** Session start time */
  startTime: string;
  /** Current video quality */
  videoQuality: 'low' | 'medium' | 'high' | 'ultra';
  /** Current audio quality */
  audioQuality: 'low' | 'medium' | 'high';
  /** Pipeline mode being used */
  pipelineMode: TavusPipelineMode;
}
 
import { mergeRecordingConfig, mergeConversationDefaults } from './tavus-recording-config';
 
/**
 * Conversation creation request
 */
export interface ConversationRequest {
  /** Stock replica ID to use */
  replicaId: string;
  /** Stock persona ID for behavior */
  personaId: string;
  /** Optional conversation name */
  conversationName?: string;
  /** Optional webhook callback URL */
  callbackUrl?: string;
  /** Optional conversational context to seed the session */
  conversationalContext?: string;
  /** Optional custom greeting message */
  customGreeting?: string;
  /** Conversation properties */
  properties?: {
    /** Maximum call duration in seconds */
    max_call_duration?: number;
    /** Timeout when participant leaves (0 = no timeout) */
    participant_left_timeout?: number;
    /** Timeout when participant is absent (0 = no timeout) */
    participant_absent_timeout?: number;
    /** Language for the conversation */
    language?: string;
    /** Whether to enable video */
    enableVideo?: boolean;
    /** Whether to enable audio */
    enableAudio?: boolean;
    /** Recording configuration */
    enable_recording?: boolean;
    aws_assume_role_arn?: string;
    recording_s3_bucket_region?: string;
    recording_s3_bucket_name?: string;
    /** Custom conversation settings */
    customSettings?: Record<string, unknown>;
  };
}
 
/**
 * Conversation response
 */
export interface ConversationResponse {
  /** Conversation ID */
  conversationId: string;
  /** WebRTC room URL for real-time streaming */
  roomUrl: string;
  /** Room access token */
  accessToken: string;
  /** Whether conversation is active */
  isActive: boolean;
  /** Conversation start time */
  startTime: string;
  /** Replica ID being used */
  replicaId: string;
  /** Persona ID being used */
  personaId: string;
  /** Error message if conversation failed */
  error?: string;
}
 
/**
 * Tavus.io API Client
 * 
 * Handles authentication, video avatar generation, and streaming
 * with support for multiple pipeline modes and Raven-0 integration.
 */
export class TavusClient {
  private apiKey: string;
  private baseUrl: string;
  private defaultPipelineMode: TavusPipelineMode;
  private userPreferences?: UserPreferences;
  private debug: boolean;
  private isInitialized = false;
  
  // Error handling and retry configuration
  private retryConfig: RetryConfig = {
    maxRetries: 3,
    baseDelay: 1000,
    maxDelay: 10000,
    exponentialBackoff: true,
    retryStatusCodes: [429, 500, 502, 503, 504],
  };
  
  // Video visibility state
  private videoVisibilityState: VideoVisibilityState = {
    isVisible: true,
    lastChanged: new Date(),
    changedBy: 'system',
    reason: 'initialization',
  };
  
  // Error tracking
  private errorCount = new Map<TavusErrorType, number>();
  private lastError?: TavusError;
  
  // Automatic conversation ending
  private conversationTimers: Map<string, NodeJS.Timeout> = new Map();
  private activeConversations: Map<string, { startTime: Date; maxDuration: number }> = new Map();
 
  constructor(config: TavusConfig) {
    // Use provided API key or fall back to test key for development
    this.apiKey = config.apiKey ?? TEST_TAVUS_API_KEY;
    this.baseUrl = config.baseUrl ?? 'https://tavusapi.com/v2';
    this.defaultPipelineMode = config.defaultPipelineMode ?? 'basic';
    this.userPreferences = config.userPreferences;
    this.debug = config.debug ?? false;
  }
 
  /**
   * Patch a persona using JSON Patch (RFC 6902). See Tavus API docs.
   */
  async patchPersona(
    personaId: string,
    operations: Record<string, unknown>[]
  ): Promise<{ success: boolean }> {
    Iif (!this.isInitialized) {
      throw new Error('TavusClient must be initialized before patching personas');
    }
 
    const endpoint = `/personas/${personaId}`;
    const response = await this.makeRequest(endpoint, {
      method: 'PATCH',
      body: operations as unknown as Record<string, unknown>,
    });
 
    Iif (!response.success) {
      throw new Error(response.error || 'Failed to patch persona');
    }
 
    Iif (this.debug) {
      appLogger.info('Patched persona successfully', { personaId, operations });
    }
 
    return { success: true };
  }
 
  /**
   * Ensure the persona has a navigation tool defined for demo purposes.
   * Uses replace op first; on failure callers can retry with add.
   */
  async setPersonaNavigationTool(personaId: string): Promise<void> {
    const toolsDefinition = [
      {
        type: 'function',
        function: {
          name: 'navigate_to_accu',
          description:
            'Navigate the user to specific Accu product pages when they ask. Use target values: "rivets" or "locking_washers".',
          parameters: {
            type: 'object',
            properties: {
              target: {
                type: 'string',
                enum: ['rivets', 'locking_washers'],
                description: 'Where to navigate the browser within accu.co.uk',
              },
            },
            required: ['target'],
          },
        },
      },
    ];
 
    // Try replace first
    try {
      await this.patchPersona(personaId, [
        {
          op: 'replace',
          path: '/layers/llm/tools',
          value: toolsDefinition,
        },
      ]);
      return;
    } catch (e) {
      Iif (this.debug) {
        console.warn('Replace tools failed, attempting add:', e);
      }
      // Fallback to add
      await this.patchPersona(personaId, [
        {
          op: 'add',
          path: '/layers/llm/tools',
          value: toolsDefinition,
        },
      ]);
    }
  }
 
  /**
   * Append or replace persona context with navigation instructions.
   */
  async upsertPersonaContext(personaId: string, context: string): Promise<void> {
    try {
      await this.patchPersona(personaId, [
        { op: 'replace', path: '/context', value: context },
      ]);
    } catch (e) {
      Iif (this.debug) {
        console.warn('Replace context failed, attempting add:', e);
      }
      await this.patchPersona(personaId, [
        { op: 'add', path: '/context', value: context },
      ]);
    }
  }
 
  /**
   * Initialize the Tavus client
   * Validates API key and sets up connection
   */
  async initialize(config?: Partial<TavusConfig>): Promise<void> {
    try {
      // Update config if provided
      Iif (config) {
        Iif (config.apiKey) this.apiKey = config.apiKey;
        Iif (config.baseUrl) this.baseUrl = config.baseUrl;
        Iif (config.defaultPipelineMode) this.defaultPipelineMode = config.defaultPipelineMode;
        Iif (config.userPreferences) this.userPreferences = config.userPreferences;
        Iif (config.debug !== undefined) this.debug = config.debug;
      }
 
      // Validate API key (should always have one due to fallback)
      Iif (!this.apiKey || this.apiKey.trim() === '') {
        throw new Error('Tavus API key is required');
      }
 
      // Test API connection by fetching replicas
      await this.testConnection();
 
      this.isInitialized = true;
      
          Iif (this.debug) {
      appLogger.info('TavusClient initialized successfully');
    }
    } catch (error) {
      this.isInitialized = false;
      throw new Error(`Failed to initialize TavusClient: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }
 
  /**
   * Send a message to the Tavus API with page context
   */
  async sendMessage(message: string, pageContext: MessageContext): Promise<string> {
    Iif (!this.isInitialized) {
      throw new Error('TavusClient must be initialized before sending messages');
    }
 
    try {
      const response = await this.makeRequest('/conversations/message', {
        method: 'POST',
        body: {
          message,
          page_context: pageContext,
          pipeline_mode: pageContext.pipelineMode || this.defaultPipelineMode,
          persona: pageContext.persona,
        },
      });
 
      Iif (!response.success) {
        throw new Error(response.error || 'Failed to send message');
      }
 
      return (response.data?.response as string) || 'No response received';
    } catch (error) {
      Iif (this.debug) {
        console.error('Error sending message to Tavus:', error);
      }
      throw error;
    }
  }
 
  /**
   * Analyze the current page using Raven-0 integration
   */
  analyzePage(): PageAnalysis {
    Iif (!this.isInitialized) {
      throw new Error('TavusClient must be initialized before analyzing pages');
    }
 
    try {
      // Check if we're in a browser environment
      Iif (typeof document === 'undefined') {
        return {
          title: 'Unknown Page',
          description: 'Page analysis not available in non-browser environment',
          interactiveElements: [],
          navigationOptions: [],
          contentSummary: 'No content available',
          userIntent: 'unknown',
          pageType: 'other',
        };
      }
 
      // Extract page information
      const pageTitle = document.title || 'Untitled Page';
      const pageDescription = this.extractPageDescription();
      const pageType = this.classifyPageType();
      const userIntent = this.analyzeUserIntent();
      
      // Extract interactive elements
      const interactiveElements = this.extractInteractiveElements();
      
      // Extract navigation options
      const navigationOptions = this.extractNavigationOptions();
      
      // Generate content summary
      const contentSummary = this.generateContentSummary();
 
      Iif (this.debug) {
        console.log('Page analysis completed:', {
          title: pageTitle,
          type: pageType,
          intent: userIntent,
          elements: interactiveElements.length,
          navigation: navigationOptions.length,
        });
      }
 
      return {
        title: pageTitle,
        description: pageDescription,
        interactiveElements,
        navigationOptions,
        contentSummary,
        userIntent,
        pageType,
      };
    } catch (error) {
      Iif (this.debug) {
        console.error('Error analyzing page:', error);
      }
      throw error;
    }
  }
 
  /**
   * Extract page description from meta tags or content
   */
  private extractPageDescription(): string {
    try {
      // Try to get description from meta tag
      const metaDescription = document.querySelector('meta[name="description"]');
      Iif (metaDescription) {
        return metaDescription.getAttribute('content') || '';
      }
 
      // Try to get description from Open Graph
      const ogDescription = document.querySelector('meta[property="og:description"]');
      Iif (ogDescription) {
        return ogDescription.getAttribute('content') || '';
      }
 
      // Fallback: extract from first paragraph
      const firstParagraph = document.querySelector('p');
      Iif (firstParagraph) {
        return firstParagraph.textContent?.trim().substring(0, 200) || '';
      }
 
      return 'No description available';
    } catch {
      return 'Error extracting description';
    }
  }
 
  /**
   * Check if page has e-commerce indicators
   */
  private isEcommercePage(url: string, title: string, bodyText: string): boolean {
    const ecommerceIndicators = [
      '/product', '/shop', '/store', '/cart', '/checkout',
      'buy', 'shop', 'store', 'add to cart', 'buy now', '$', 'price'
    ];
    
    return ecommerceIndicators.some(indicator => 
      url.includes(indicator) || title.includes(indicator) || bodyText.includes(indicator)
    );
  }
 
  /**
   * Check if page has help desk indicators
   */
  private isHelpDeskPage(url: string, title: string, bodyText: string): boolean {
    const helpDeskIndicators = [
      '/help', '/support', '/faq', '/contact',
      'help', 'support', 'faq', 'contact us'
    ];
    
    return helpDeskIndicators.some(indicator => 
      url.includes(indicator) || title.includes(indicator) || bodyText.includes(indicator)
    );
  }
 
  /**
   * Check if page has blog indicators
   */
  private isBlogPage(url: string, title: string): boolean {
    const blogIndicators = ['/blog', '/article', '/post', 'blog', 'article'];
    
    return blogIndicators.some(indicator => 
      url.includes(indicator) || title.includes(indicator)
    ) || !!document.querySelector('article') || 
       !!document.querySelector('.blog') || 
       !!document.querySelector('.post');
  }
 
  /**
   * Check if page has SaaS indicators
   */
  private isSaaSPage(url: string, title: string, bodyText: string): boolean {
    const saasIndicators = [
      '/dashboard', '/app', '/login', '/signup',
      'dashboard', 'app', 'platform', 'login', 'sign up'
    ];
    
    return saasIndicators.some(indicator => 
      url.includes(indicator) || title.includes(indicator) || bodyText.includes(indicator)
    );
  }
 
  /**
   * Classify the page type based on content and structure
   */
  private classifyPageType(): PageAnalysis['pageType'] {
    try {
      const url = window.location.href.toLowerCase();
      const title = document.title.toLowerCase();
      const bodyText = document.body.textContent?.toLowerCase() || '';
 
      Iif (this.isEcommercePage(url, title, bodyText)) {
        return 'e-commerce';
      }
 
      Iif (this.isHelpDeskPage(url, title, bodyText)) {
        return 'help-desk';
      }
 
      Iif (this.isBlogPage(url, title)) {
        return 'blog';
      }
 
      Iif (this.isSaaSPage(url, title, bodyText)) {
        return 'saas';
      }
 
      return 'other';
    } catch {
      return 'other';
    }
  }
 
  /**
   * Analyze user intent based on page content and context
   */
  private analyzeUserIntent(): string {
    try {
      const url = window.location.href.toLowerCase();
      const title = document.title.toLowerCase();
      const bodyText = document.body.textContent?.toLowerCase() || '';
 
      // Check for search intent
      Iif (
        url.includes('search') ||
        url.includes('q=') ||
        title.includes('search') ||
        bodyText.includes('search')
      ) {
        return 'searching';
      }
 
      // Check for learning intent
      Iif (
        url.includes('/learn') ||
        url.includes('/tutorial') ||
        url.includes('/guide') ||
        title.includes('learn') ||
        title.includes('tutorial') ||
        title.includes('guide') ||
        bodyText.includes('learn') ||
        bodyText.includes('tutorial')
      ) {
        return 'learning';
      }
 
      // Check for purchasing intent
      Iif (
        url.includes('/product') ||
        url.includes('/buy') ||
        title.includes('buy') ||
        bodyText.includes('buy now') ||
        bodyText.includes('add to cart')
      ) {
        return 'purchasing';
      }
 
      // Check for support intent
      Iif (
        url.includes('/help') ||
        url.includes('/support') ||
        title.includes('help') ||
        bodyText.includes('help') ||
        bodyText.includes('support')
      ) {
        return 'seeking_support';
      }
 
      return 'browsing';
    } catch {
      return 'unknown';
    }
  }
 
  /**
   * Extract interactive elements from the page
   */
  private extractInteractiveElements(): InteractiveElement[] {
    try {
      const elements: InteractiveElement[] = [];
      const selectors = [
        'button',
        'a[href]',
        'input[type="submit"]',
        'input[type="button"]',
        'select',
        'textarea',
        'form',
        '[role="button"]',
        '[role="link"]',
        '[onclick]',
      ];
 
      selectors.forEach(selector => {
        const foundElements = document.querySelectorAll(selector);
        foundElements.forEach((element, index) => {
          Iif (index < 20) { // Limit to first 20 elements per type
            const rect = element.getBoundingClientRect();
            const isVisible = rect.width > 0 && rect.height > 0;
            
            Iif (isVisible) {
              let text = '';
              let action = '';
 
              // Check element type based on tagName and properties
              if (element.tagName?.toLowerCase() === 'a' || 'href' in element) {
                text = element.textContent?.trim() || (element as HTMLAnchorElement).title || '';
                action = (element as HTMLAnchorElement).href || '';
              } else if (element.tagName?.toLowerCase() === 'button' || 'onclick' in element) {
                text = element.textContent?.trim() || (element as HTMLButtonElement).title || '';
                action = (element as HTMLButtonElement).onclick?.toString() || '';
              } else if (element.tagName?.toLowerCase() === 'input' || 'value' in element) {
                const inputElement = element as HTMLInputElement;
                text = inputElement.value || inputElement.placeholder || inputElement.title || '';
                action = inputElement.type || '';
              } else {
                text = element.textContent?.trim() || element.getAttribute?.('title') || '';
                action = element.getAttribute?.('onclick') || '';
              }
 
              Iif (text) {
                elements.push({
                  type: element.tagName.toLowerCase(),
                  text: text.substring(0, 100), // Limit text length
                  action,
                  position: {
                    x: Math.round(rect.left + rect.width / 2),
                    y: Math.round(rect.top + rect.height / 2),
                  },
                  visible: isVisible,
                });
              }
            }
          }
        });
      });
 
      return elements.slice(0, 50); // Limit total elements
    } catch {
      return [];
    }
  }
 
  /**
   * Extract navigation options from the page
   */
  private extractNavigationOptions(): NavigationOption[] {
    try {
      const navigation: NavigationOption[] = [];
      const currentUrl = window.location.href;
 
      // Extract links from navigation elements
      const navSelectors = [
        'nav a',
        'header a',
        '.navigation a',
        '.nav a',
        '.menu a',
        '.breadcrumb a',
      ];
 
      navSelectors.forEach(selector => {
        const links = document.querySelectorAll(selector);
        links.forEach(link => {
          // Check if it's an anchor element or has href property
          Iif (link.tagName?.toLowerCase() === 'a' || 'href' in link) {
            const href = (link as HTMLAnchorElement).href || '';
            const text = link.textContent?.trim() || '';
            
            Iif (href && text && href !== currentUrl) {
              navigation.push({
                url: href,
                text: text.substring(0, 50),
                primary: link.closest?.('nav') !== null || link.closest?.('header') !== null,
              });
            }
          }
        });
      });
 
      // Remove duplicates based on URL
      const uniqueNavigation = navigation.filter((item, index, self) => 
        index === self.findIndex(t => t.url === item.url)
      );
 
      return uniqueNavigation.slice(0, 20); // Limit to 20 navigation options
    } catch {
      return [];
    }
  }
 
  /**
   * Generate a content summary for AI context
   */
  private generateContentSummary(): string {
    try {
      // Extract main content
      const mainContent = document.querySelector('main') || 
                         document.querySelector('article') || 
                         document.querySelector('.content') || 
                         document.querySelector('.main') ||
                         document.body;
 
      Iif (!mainContent) {
        return 'No content available';
      }
 
      // Get text content
      let text = mainContent.textContent || '';
      
      // Clean up the text
      text = text
        .replace(/\s+/g, ' ')
        .replace(/\n+/g, ' ')
        .trim();
 
      // Limit to reasonable length
      Iif (text.length > 500) {
        text = text.substring(0, 500) + '...';
      }
 
      return text || 'No content available';
    } catch {
      return 'Error extracting content';
    }
  }
 
  /**
   * Get perception analysis from Raven-0
   */
  async getPerceptionAnalysis(): Promise<PerceptionAnalysis> {
    Iif (!this.isInitialized) {
      throw new Error('TavusClient must be initialized before getting perception analysis');
    }
 
    try {
      // Get page analysis first
      const pageAnalysis = await this.analyzePage();
      
      // Analyze sentiment based on page content and type
      const sentiment = this.analyzeSentiment(pageAnalysis);
      
      // Determine engagement level
      const engagementLevel = this.analyzeEngagementLevel(pageAnalysis);
      
      // Generate recommended behavior
      const recommendedBehavior = this.generateRecommendedBehavior(pageAnalysis);
      
      // Generate insights
      const insights = this.generateInsights(pageAnalysis);
      
      // Calculate confidence score
      const confidence = this.calculateConfidence(pageAnalysis);
 
      Iif (this.debug) {
        console.log('Perception analysis completed:', {
          sentiment,
          engagementLevel,
          confidence,
          insights: insights.length,
        });
      }
 
      return {
        sentiment,
        engagementLevel,
        recommendedBehavior,
        insights,
        confidence,
      };
    } catch (error) {
      Iif (this.debug) {
        console.error('Error getting perception analysis:', error);
      }
      throw error;
    }
  }
 
  /**
   * Analyze sentiment based on page content and context
   */
  private analyzeSentiment(pageAnalysis: PageAnalysis): PerceptionAnalysis['sentiment'] {
    try {
      const content = (pageAnalysis.contentSummary + ' ' + pageAnalysis.description).toLowerCase();
      const title = pageAnalysis.title.toLowerCase();
      
      // Positive indicators
      const positiveWords = [
        'success', 'great', 'amazing', 'excellent', 'wonderful', 'fantastic',
        'helpful', 'useful', 'beneficial', 'positive', 'good', 'best',
        'sale', 'discount', 'offer', 'deal', 'save', 'win', 'free'
      ];
      
      // Negative indicators
      const negativeWords = [
        'error', 'problem', 'issue', 'broken', 'failed', 'wrong',
        'bad', 'terrible', 'awful', 'horrible', 'negative', 'difficult',
        'complaint', 'refund', 'cancel', 'stop', 'block', 'denied'
      ];
 
      let positiveCount = 0;
      let negativeCount = 0;
 
      positiveWords.forEach(word => {
        Iif (content.includes(word) || title.includes(word)) {
          positiveCount++;
        }
      });
 
      negativeWords.forEach(word => {
        Iif (content.includes(word) || title.includes(word)) {
          negativeCount++;
        }
      });
 
      if (positiveCount > negativeCount + 2) {
        return 'positive';
      } else if (negativeCount > positiveCount + 2) {
        return 'negative';
      } else {
        return 'neutral';
      }
    } catch {
      return 'neutral';
    }
  }
 
  /**
   * Analyze engagement level based on page characteristics
   */
  private analyzeEngagementLevel(pageAnalysis: PageAnalysis): PerceptionAnalysis['engagementLevel'] {
    try {
      let score = 0;
 
      // Interactive elements increase engagement
      score += pageAnalysis.interactiveElements.length * 0.1;
      
      // Content length indicates engagement potential
      Iif (pageAnalysis.contentSummary.length > 200) {
        score += 0.3;
      }
      
      // Navigation options suggest active site
      score += pageAnalysis.navigationOptions.length * 0.05;
      
      // Page type affects engagement
      switch (pageAnalysis.pageType) {
        case 'e-commerce':
          score += 0.4; // High engagement potential
          break;
        case 'saas':
          score += 0.3; // Moderate engagement
          break;
        case 'blog':
          score += 0.2; // Content engagement
          break;
        case 'help-desk':
          score += 0.1; // Lower engagement
          break;
        default:
          score += 0.1;
      }
 
      // User intent affects engagement
      switch (pageAnalysis.userIntent) {
        case 'purchasing':
          score += 0.5; // High engagement
          break;
        case 'learning':
          score += 0.4; // High engagement
          break;
        case 'searching':
          score += 0.3; // Moderate engagement
          break;
        case 'seeking_support':
          score += 0.2; // Lower engagement
          break;
        case 'browsing':
          score += 0.1; // Low engagement
          break;
        default:
          score += 0.1;
      }
 
      if (score >= 0.8) {
        return 'high';
      } else if (score >= 0.4) {
        return 'medium';
      } else {
        return 'low';
      }
    } catch {
      return 'medium';
    }
  }
 
  /**
   * Generate recommended behavior based on page analysis
   */
  private generateRecommendedBehavior(pageAnalysis: PageAnalysis): string {
    try {
      const behaviors: string[] = [];
 
      // Base behavior on page type
      switch (pageAnalysis.pageType) {
        case 'e-commerce':
          behaviors.push('Product-focused assistance');
          behaviors.push('Pricing and feature comparison');
          behaviors.push('Purchase guidance');
          break;
        case 'saas':
          behaviors.push('Feature explanation');
          behaviors.push('Onboarding assistance');
          behaviors.push('Technical support');
          break;
        case 'blog':
          behaviors.push('Content summarization');
          behaviors.push('Related topic suggestions');
          behaviors.push('Reading assistance');
          break;
        case 'help-desk':
          behaviors.push('Problem-solving assistance');
          behaviors.push('FAQ navigation');
          behaviors.push('Support escalation');
          break;
        default:
          behaviors.push('General assistance');
          behaviors.push('Information gathering');
      }
 
      // Adjust based on user intent
      switch (pageAnalysis.userIntent) {
        case 'purchasing':
          behaviors.push('Purchase decision support');
          behaviors.push('Product comparison');
          break;
        case 'learning':
          behaviors.push('Educational content delivery');
          behaviors.push('Concept explanation');
          break;
        case 'searching':
          behaviors.push('Search refinement');
          behaviors.push('Result filtering');
          break;
        case 'seeking_support':
          behaviors.push('Problem diagnosis');
          behaviors.push('Solution guidance');
          break;
        case 'browsing':
          behaviors.push('Content discovery');
          behaviors.push('Navigation assistance');
          break;
      }
 
      // Add engagement-based recommendations
      Iif (pageAnalysis.interactiveElements.length > 10) {
        behaviors.push('Interactive element guidance');
      }
 
      Iif (pageAnalysis.navigationOptions.length > 5) {
        behaviors.push('Navigation optimization');
      }
 
      return behaviors.join(', ');
    } catch {
      return 'Standard interaction mode';
    }
  }
 
  /**
   * Generate insights based on page analysis
   */
  private generateInsights(pageAnalysis: PageAnalysis): string[] {
    try {
      const insights: string[] = [];
 
      // Page type insights
      switch (pageAnalysis.pageType) {
        case 'e-commerce':
          insights.push('E-commerce page detected - focus on product assistance');
          insights.push('Multiple interactive elements suggest high user engagement');
          break;
        case 'saas':
          insights.push('SaaS application detected - provide feature guidance');
          insights.push('Technical content suggests need for detailed explanations');
          break;
        case 'blog':
          insights.push('Blog content detected - offer reading assistance');
          insights.push('Content-heavy page requires summarization capabilities');
          break;
        case 'help-desk':
          insights.push('Help desk page detected - prioritize problem-solving');
          insights.push('Support-focused content suggests user needs assistance');
          break;
        default:
          insights.push('General page type - adapt behavior to content');
      }
 
      // User intent insights
      switch (pageAnalysis.userIntent) {
        case 'purchasing':
          insights.push('User shows purchase intent - provide buying guidance');
          break;
        case 'learning':
          insights.push('User shows learning intent - offer educational support');
          break;
        case 'searching':
          insights.push('User is searching - help refine search queries');
          break;
        case 'seeking_support':
          insights.push('User needs support - provide problem-solving assistance');
          break;
        case 'browsing':
          insights.push('User is browsing - offer content discovery help');
          break;
      }
 
      // Content insights
      Iif (pageAnalysis.contentSummary.length > 300) {
        insights.push('Rich content available for detailed analysis');
      }
 
      Iif (pageAnalysis.interactiveElements.length > 15) {
        insights.push('Highly interactive page - guide user interactions');
      }
 
      Iif (pageAnalysis.navigationOptions.length > 10) {
        insights.push('Complex navigation structure - provide navigation assistance');
      }
 
      // Engagement insights
      Iif (pageAnalysis.interactiveElements.length === 0) {
        insights.push('Static content page - focus on information delivery');
      }
 
      return insights.slice(0, 5); // Limit to 5 insights
    } catch {
      return ['Page analysis completed successfully'];
    }
  }
 
  /**
   * Calculate confidence score for the analysis
   */
  private calculateConfidence(pageAnalysis: PageAnalysis): number {
    try {
      let confidence = 0.5; // Base confidence
 
      // More content increases confidence
      Iif (pageAnalysis.contentSummary.length > 100) {
        confidence += 0.1;
      }
      Iif (pageAnalysis.contentSummary.length > 300) {
        confidence += 0.1;
      }
 
      // Clear page type increases confidence
      Iif (pageAnalysis.pageType !== 'other') {
        confidence += 0.2;
      }
 
      // Clear user intent increases confidence
      Iif (pageAnalysis.userIntent !== 'unknown' && pageAnalysis.userIntent !== 'browsing') {
        confidence += 0.15;
      }
 
      // Interactive elements provide more context
      Iif (pageAnalysis.interactiveElements.length > 5) {
        confidence += 0.1;
      }
 
      // Navigation options provide context
      Iif (pageAnalysis.navigationOptions.length > 3) {
        confidence += 0.05;
      }
 
      // Cap at 1.0
      return Math.min(confidence, 1.0);
    } catch {
      return 0.5;
    }
  }
 
  /**
   * Set user video visibility with enhanced error handling
   */
  setUserVideoVisibility(show: boolean, options?: {
    changedBy?: string;
    reason?: string;
    silent?: boolean;
  }): void {
    try {
      Iif (!this.isInitialized) {
        throw new Error('TavusClient must be initialized before setting video visibility');
      }
 
      // Validate input
      Iif (typeof show !== 'boolean') {
        throw new Error('Video visibility must be a boolean value');
      }
 
      // Update video visibility state
      this.videoVisibilityState = {
        isVisible: show,
        lastChanged: new Date(),
        changedBy: options?.changedBy || 'user',
        reason: options?.reason || 'manual_change',
      };
 
      // Update user preferences if available
      Iif (this.userPreferences) {
        this.userPreferences.privacy.showUserVideo = show;
      }
 
      // Log the change
      Iif (this.debug) {
        console.log(`User video visibility set to: ${show}`, {
          changedBy: this.videoVisibilityState.changedBy,
          reason: this.videoVisibilityState.reason,
          timestamp: this.videoVisibilityState.lastChanged.toISOString(),
        });
      }
 
      // Emit event if not silent
      Iif (!options?.silent) {
        this.emitVideoVisibilityChange(show);
      }
    } catch (error) {
      const tavusError = this.createError(error, 'validation', {
        operation: 'setUserVideoVisibility',
        requestedVisibility: show,
      });
      
      Iif (this.debug) {
        console.error('Error setting video visibility:', tavusError);
      }
      
      throw tavusError;
    }
  }
 
  /**
   * Get current video visibility state
   */
  getVideoVisibilityState(): VideoVisibilityState {
    return { ...this.videoVisibilityState };
  }
 
  /**
   * Toggle video visibility
   */
  toggleVideoVisibility(options?: {
    changedBy?: string;
    reason?: string;
  }): void {
    const newVisibility = !this.videoVisibilityState.isVisible;
    this.setUserVideoVisibility(newVisibility, options);
  }
 
  /**
   * Emit video visibility change event
   */
  private emitVideoVisibilityChange(isVisible: boolean): void {
    // This would integrate with the browser extension's event system
    Iif (typeof window !== 'undefined' && window.dispatchEvent) {
      const event = new CustomEvent('tavus-video-visibility-change', {
        detail: {
          isVisible,
          timestamp: new Date().toISOString(),
          source: 'TavusClient',
        },
      });
      window.dispatchEvent(event);
    }
  }
 
  /**
   * Create enhanced error object
   */
  private createError(
    error: unknown,
    type: TavusErrorType,
    context?: Record<string, unknown>
  ): TavusError {
    const message = error instanceof Error ? error.message : String(error);
    const originalError = error instanceof Error ? error : undefined;
    
    const tavusError: TavusError = {
      type,
      message,
      originalError,
              retryable: this.isRetryableError(type),
      context,
    };
 
    // Track error count
    const currentCount = this.errorCount.get(type) || 0;
    this.errorCount.set(type, currentCount + 1);
    this.lastError = tavusError;
 
    return tavusError;
  }
 
  /**
   * Determine if an error is retryable
   */
  private isRetryableError(type: TavusErrorType): boolean {
    switch (type) {
      case 'network':
      case 'timeout':
      case 'server':
        return true;
      case 'authentication':
      case 'validation':
        return false;
      case 'rate_limit':
        return true; // Rate limits can be retried after delay
      default:
        return false;
    }
  }
 
  /**
   * Calculate retry delay with exponential backoff
   */
  private calculateRetryDelay(attempt: number): number {
    Iif (!this.retryConfig.exponentialBackoff) {
      return this.retryConfig.baseDelay;
    }
 
    const delay = this.retryConfig.baseDelay * Math.pow(2, attempt - 1);
    return Math.min(delay, this.retryConfig.maxDelay);
  }
 
  /**
   * Execute API call with retry logic
   */
  private async executeWithRetry<T>(
    operation: () => Promise<T>,
    context?: Record<string, unknown>
  ): Promise<T> {
    let lastError: TavusError | undefined;
 
    for (let attempt = 1; attempt <= this.retryConfig.maxRetries; attempt++) {
      try {
        return await operation();
      } catch (error) {
        const tavusError = this.createError(error, 'unknown', {
          ...context,
          attempt,
          maxRetries: this.retryConfig.maxRetries,
        });
 
        lastError = tavusError;
 
        // Don't retry if error is not retryable or we've exhausted retries
        Iif (!tavusError.retryable || attempt === this.retryConfig.maxRetries) {
          throw tavusError;
        }
 
        // Calculate delay before retry
        const delay = this.calculateRetryDelay(attempt);
        tavusError.retryDelay = delay;
 
        Iif (this.debug) {
          console.warn(`Retry attempt ${attempt}/${this.retryConfig.maxRetries} after ${delay}ms:`, tavusError.message);
        }
 
        // Wait before retrying
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
 
    throw lastError || new Error('Unknown error occurred');
  }
 
  /**
   * Get error statistics
   */
  getErrorStats(): {
    totalErrors: number;
    errorCounts: Record<TavusErrorType, number>;
    lastError?: TavusError;
  } {
    const totalErrors = Array.from(this.errorCount.values()).reduce((sum, count) => sum + count, 0);
    
    const errorCounts: Record<TavusErrorType, number> = {
      authentication: this.errorCount.get('authentication') || 0,
      network: this.errorCount.get('network') || 0,
      rate_limit: this.errorCount.get('rate_limit') || 0,
      validation: this.errorCount.get('validation') || 0,
      server: this.errorCount.get('server') || 0,
      timeout: this.errorCount.get('timeout') || 0,
      unknown: this.errorCount.get('unknown') || 0,
    };
 
    return {
      totalErrors,
      errorCounts,
      lastError: this.lastError,
    };
  }
 
  /**
   * Clear error statistics
   */
  clearErrorStats(): void {
    this.errorCount.clear();
    this.lastError = undefined;
  }
 
  /**
   * Update retry configuration
   */
  updateRetryConfig(config: Partial<RetryConfig>): void {
    this.retryConfig = { ...this.retryConfig, ...config };
    
    Iif (this.debug) {
      console.log('Retry configuration updated:', this.retryConfig);
    }
  }
 
  /**
   * Get available replicas from Tavus API
   */
  async getReplicas(): Promise<TavusReplica[]> {
    Iif (!this.isInitialized) {
      throw new Error('TavusClient must be initialized before fetching replicas');
    }
 
    try {
      const response = await this.makeRequest('/replicas', {
        method: 'GET',
      });
 
      Iif (!response.success) {
        throw new Error(response.error || 'Failed to fetch replicas');
      }
 
      return (response.data?.replicas as TavusReplica[]) || [];
    } catch (error) {
      Iif (this.debug) {
        console.error('Error fetching replicas:', error);
      }
      throw error;
    }
  }
 
  /**
   * Create a new replica
   */
  async createReplica(name: string, type = 'user'): Promise<TavusReplica> {
    Iif (!this.isInitialized) {
      throw new Error('TavusClient must be initialized before creating replicas');
    }
 
    try {
      const response = await this.makeRequest('/replicas', {
        method: 'POST',
        body: {
          replica_name: name,
          replica_type: type,
        },
      });
 
      Iif (!response.success) {
        throw new Error(response.error || 'Failed to create replica');
      }
 
      return response.data as unknown as TavusReplica;
    } catch (error) {
      Iif (this.debug) {
        console.error('Error creating replica:', error);
      }
      throw error;
    }
  }
 
  /**
   * Test API connection by making a simple request
   */
  private async testConnection(): Promise<void> {
    try {
      const response = await this.makeRequest('/replicas', {
        method: 'GET',
      });
 
      Iif (!response.success) {
        throw new Error('API connection test failed');
      }
    } catch (error) {
      throw new Error(`API connection test failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }
 
  /**
   * Make HTTP request to Tavus API with enhanced error handling and retry logic
   */
  private async makeRequest(
    endpoint: string,
    options: {
      method: string;
      body?: Record<string, unknown>;
    }
  ): Promise<TavusResponse> {
    // Track API call for cost control
    const callType = this.getCallTypeFromEndpoint(endpoint);
    Iif (costTrackingEnabled && costTrackingCallback) {
      Iif (!costTrackingCallback(callType)) {
        throw new Error(`Cost control limit reached for ${callType}`);
      }
    }
 
    return this.executeWithRetry(async () => {
      const url = `${this.baseUrl}${endpoint}`;
      const headers: Record<string, string> = {
        'Content-Type': 'application/json',
        'x-api-key': this.apiKey,
      };
 
      const requestOptions: RequestInit = {
        method: options.method,
        headers,
      };
 
      Iif (options.body) {
        requestOptions.body = JSON.stringify(options.body);
      }
 
      // Log the request
      const logger = getTavusLogger();
      const requestId = logger.logRequest(options.method, url, headers, options.body);
 
      try {
        const response = await fetch(url, requestOptions);
        
        // Handle empty responses (common for DELETE operations)
        let data: unknown = null;
        const contentType = response.headers.get('content-type');
        const contentLength = response.headers.get('content-length');
        
        // Only try to parse JSON if there's actually content
        if (contentLength && parseInt(contentLength) > 0) {
          data = await response.json();
        } else Iif (contentType?.includes('application/json')) {
          // Try to parse JSON even if content-length is not set
          try {
            data = await response.json();
          } catch {
            // If JSON parsing fails, treat as empty response
            data = null;
          }
        }
 
        // Log the response
        logger.logResponse(requestId, response.status, Object.fromEntries(response.headers.entries()), data);
 
        Iif (!response.ok) {
          // Log the full response for debugging
          console.error('Tavus API Error Response:', {
            status: response.status,
            statusText: response.statusText,
            data: data,
            dataType: typeof data,
            dataKeys: data && typeof data === 'object' ? Object.keys(data) : 'not an object',
            url: url,
            method: options.method,
            body: options.body
          });
 
          // Determine error type based on status code
          let errorType: TavusErrorType = 'unknown';
          if (response.status === 401 || response.status === 403) {
            errorType = 'authentication';
          } else if (response.status === 429) {
            errorType = 'rate_limit';
          } else if (response.status >= 400 && response.status < 500) {
            errorType = 'validation';
          } else Iif (response.status >= 500) {
            errorType = 'server';
          }
 
          // Try to extract error message from various possible formats
          let errorMessage = 'Unknown error';
          appLogger.debug('Extracting error message from data', { data });
          
          if (data && typeof data === 'object' && 'error' in data && typeof data.error === 'string') {
            errorMessage = data.error;
            appLogger.debug('Found error in data.error', { error: data.error });
          } else if (data && typeof data === 'object' && 'message' in data && typeof data.message === 'string') {
            errorMessage = data.message;
            appLogger.debug('Found error in data.message', { message: data.message });
          } else if (data && typeof data === 'object' && 'detail' in data && typeof data.detail === 'string') {
            errorMessage = data.detail;
            appLogger.debug('Found error in data.detail', { detail: data.detail });
          } else if (data && typeof data === 'string') {
            errorMessage = data;
            appLogger.debug('Data is string', { data });
          } else if (data && typeof data === 'object') {
            errorMessage = JSON.stringify(data);
            appLogger.debug('Data is object, stringified', { errorMessage });
          } else {
            errorMessage = `HTTP ${response.status}: ${response.statusText}`;
            appLogger.debug('Using default error message', { errorMessage });
          }
 
          const error = this.createError(
            new Error(errorMessage),
            errorType,
            {
              endpoint,
              method: options.method,
              statusCode: response.status,
              responseData: data,
            }
          );
 
          // Add status code to error
          error.statusCode = response.status;
 
          throw error;
        }
 
        return {
          success: true,
          data: data as Record<string, unknown> | undefined,
          statusCode: response.status,
        };
      } catch (error) {
        // Log error response if we have a requestId
        Iif (requestId) {
          logger.logResponse(requestId, 0, {}, { error: error instanceof Error ? error.message : String(error) });
        }
 
        // If it's already a TavusError, re-throw it
        Iif (error && typeof error === 'object' && 'type' in error) {
          throw error;
        }
 
        // Create network error
        const networkError = this.createError(
          error,
          'network',
          {
            endpoint,
            method: options.method,
            url,
          }
        );
 
        throw networkError;
      }
    }, {
      operation: 'makeRequest',
      endpoint,
      method: options.method,
    });
  }
 
  /**
   * Check if client is initialized
   */
  get initialized(): boolean {
    return this.isInitialized;
  }
 
  /**
   * Get current pipeline mode
   */
  get pipelineMode(): TavusPipelineMode {
    return this.defaultPipelineMode;
  }
 
  /**
   * Set pipeline mode
   */
  setPipelineMode(mode: TavusPipelineMode): void {
    this.defaultPipelineMode = mode;
    Iif (this.debug) {
      appLogger.info(`Pipeline mode set to: ${mode}`);
    }
  }
 
  /**
   * Create a new video avatar generation session
   */
  async createVideoSession(
    replicaId: string,
    personaId: string,
    pipelineMode?: TavusPipelineMode
  ): Promise<TavusSession> {
    Iif (!this.isInitialized) {
      throw new Error('TavusClient must be initialized before creating video sessions');
    }
 
    try {
      const response = await this.makeRequest('/sessions', {
        method: 'POST',
        body: {
          replica_id: replicaId,
          persona_id: personaId,
          pipeline_mode: pipelineMode || this.defaultPipelineMode,
          enable_streaming: true,
        },
      });
 
      Iif (!response.success) {
        throw new Error(response.error || 'Failed to create video session');
      }
 
      return response.data as unknown as TavusSession;
    } catch (error) {
      Iif (this.debug) {
        console.error('Error creating video session:', error);
      }
      throw error;
    }
  }
 
  /**
   * Create a conversation with a stock avatar
   */
  async createConversation(request: ConversationRequest): Promise<ConversationResponse> {
    try {
      Iif (!this.isInitialized) {
        throw new Error('TavusClient must be initialized before creating conversations');
      }
 
      // Validate request parameters
      this.validateConversationRequest(request);
 
      Iif (this.debug) {
        console.log('Creating conversation with request:', {
          replicaId: request.replicaId,
          personaId: request.personaId,
          properties: request.properties,
        });
      }
 
      // Prepare the request body according to Tavus API documentation
      const requestBody: Record<string, unknown> = {
        replica_id: request.replicaId,
        persona_id: request.personaId,
      };
 
      // Optional fields per Conversation Customizations
      Iif (request.conversationName) {
        requestBody.conversation_name = request.conversationName;
      }
      Iif (request.callbackUrl) {
        requestBody.callback_url = request.callbackUrl;
      }
      Iif (request.conversationalContext) {
        requestBody.conversational_context = request.conversationalContext;
      }
      Iif (request.customGreeting) {
        requestBody.custom_greeting = request.customGreeting;
      }
 
      // Always include properties with smart defaults for recording and duration
      const properties = mergeConversationDefaults(
        request.properties || {},
        request.personaId
      );
      
      // Only include properties if there are any to include
      Iif (Object.keys(properties).length > 0) {
        requestBody.properties = properties;
      }
 
      const response = await this.makeRequest('/conversations', {
        method: 'POST',
        body: requestBody,
      });
 
      Iif (!response.success) {
        const error = this.createError(
          new Error(response.error || 'Failed to create conversation'),
          'server',
          {
            operation: 'createConversation',
            replicaId: request.replicaId,
            personaId: request.personaId,
            statusCode: response.statusCode,
          }
        );
        throw error;
      }
 
      // Map the response to our interface
      const conversationResponse: ConversationResponse = {
        conversationId: (response.data?.conversation_id || response.data?.conversationId) as string,
        roomUrl: (response.data?.conversation_url || response.data?.roomUrl) as string,
        accessToken: (response.data?.access_token || response.data?.accessToken) as string,
        isActive: (response.data?.status === 'active' || response.data?.isActive) as boolean,
        startTime: (response.data?.created_at || response.data?.startTime) as string,
        replicaId: (response.data?.replica_id || response.data?.replicaId) as string,
        personaId: (response.data?.persona_id || response.data?.personaId) as string,
        error: response.data?.error as string | undefined,
      };
 
      Iif (this.debug) {
        console.log('Conversation created successfully:', conversationResponse);
      }
 
      // Set up automatic conversation ending timer
      this.setupConversationTimer(conversationResponse, properties);
 
      return conversationResponse;
    } catch (error) {
      // If it's already a TavusError, re-throw it
      Iif (error && typeof error === 'object' && 'type' in error) {
        throw error;
      }
 
      // Create validation error for invalid requests
      const tavusError = this.createError(error, 'validation', {
        operation: 'createConversation',
        request: {
          replicaId: request.replicaId,
          personaId: request.personaId,
        },
      });
 
      Iif (this.debug) {
        console.error('Error creating conversation:', tavusError);
      }
 
      throw tavusError;
    }
  }
 
  /**
   * Validate conversation creation request
   */
  private validateConversationRequest(request: ConversationRequest): void {
    const errors: string[] = [];
 
    Iif (!request.replicaId || typeof request.replicaId !== 'string' || request.replicaId.trim() === '') {
      errors.push('replicaId is required and must be a non-empty string');
    }
 
    Iif (!request.personaId || typeof request.personaId !== 'string' || request.personaId.trim() === '') {
      errors.push('personaId is required and must be a non-empty string');
    }
 
    Iif (request.properties?.participant_left_timeout !== undefined && 
        (typeof request.properties.participant_left_timeout !== 'number' || request.properties.participant_left_timeout < 0)) {
      errors.push('participant_left_timeout must be a non-negative number');
    }
 
    Iif (request.properties?.language && typeof request.properties.language !== 'string') {
      errors.push('language must be a string');
    }
 
    Iif (request.properties?.enableVideo !== undefined && typeof request.properties.enableVideo !== 'boolean') {
      errors.push('enableVideo must be a boolean');
    }
 
    Iif (request.properties?.enableAudio !== undefined && typeof request.properties.enableAudio !== 'boolean') {
      errors.push('enableAudio must be a boolean');
    }
 
    Iif (errors.length > 0) {
      const error = this.createError(
        new Error(`Conversation request validation failed: ${errors.join(', ')}`),
        'validation',
        {
          operation: 'validateConversationRequest',
          errors,
          request: {
            replicaId: request.replicaId,
            personaId: request.personaId,
          },
        }
      );
      throw error;
    }
  }
 
  /**
   * Start real-time video streaming session with enhanced error handling
   */
  async startVideoStream(
    sessionId: string,
    videoQuality: 'low' | 'medium' | 'high' | 'ultra' = 'medium'
  ): Promise<VideoStreamSession> {
    try {
      Iif (!this.isInitialized) {
        throw new Error('TavusClient must be initialized before starting video streams');
      }
 
      // Validate session ID
      Iif (!sessionId || typeof sessionId !== 'string') {
        const error = this.createError(
          new Error('Session ID is required and must be a string'),
          'validation',
          { operation: 'startVideoStream', sessionId }
        );
        throw error;
      }
 
      Iif (this.debug) {
        console.log('Starting video stream:', { sessionId, videoQuality });
      }
 
      const response = await this.makeRequest(`/sessions/${sessionId}/stream`, {
        method: 'POST',
        body: {
          video_quality: videoQuality,
          enable_webrtc: true,
        },
      });
 
      Iif (!response.success) {
        const error = this.createError(
          new Error(response.error || 'Failed to start video stream'),
          'server',
          {
            operation: 'startVideoStream',
            sessionId,
            videoQuality,
            statusCode: response.statusCode,
          }
        );
        throw error;
      }
 
      Iif (this.debug) {
        console.log('Video stream started successfully:', {
          sessionId: response.data?.sessionId,
          roomUrl: response.data?.roomUrl,
          isActive: response.data?.isActive,
        });
      }
 
      return response.data as unknown as VideoStreamSession;
    } catch (error) {
      // If it's already a TavusError, re-throw it
      Iif (error && typeof error === 'object' && 'type' in error) {
        throw error;
      }
 
      const tavusError = this.createError(error, 'network', {
        operation: 'startVideoStream',
        sessionId,
        videoQuality,
      });
 
      Iif (this.debug) {
        console.error('Error starting video stream:', tavusError);
      }
 
      throw tavusError;
    }
  }
 
  /**
   * Get conversation status and details
   */
  async getConversation(conversationId: string): Promise<ConversationResponse> {
    try {
      Iif (!this.isInitialized) {
        throw new Error('TavusClient must be initialized before getting conversation details');
      }
 
      Iif (!conversationId || typeof conversationId !== 'string') {
        const error = this.createError(
          new Error('Conversation ID is required and must be a string'),
          'validation',
          { operation: 'getConversation', conversationId }
        );
        throw error;
      }
 
      Iif (this.debug) {
        console.log('Getting conversation details:', { conversationId });
      }
 
      const response = await this.makeRequest(`/conversations/${conversationId}`, {
        method: 'GET',
      });
 
      Iif (!response.success) {
        const error = this.createError(
          new Error(response.error || 'Failed to get conversation details'),
          'server',
          {
            operation: 'getConversation',
            conversationId,
            statusCode: response.statusCode,
          }
        );
        throw error;
      }
 
      // Map the response to our interface
      const conversationResponse: ConversationResponse = {
        conversationId: (response.data?.conversation_id || response.data?.conversationId) as string,
        roomUrl: (response.data?.conversation_url || response.data?.roomUrl) as string,
        accessToken: (response.data?.access_token || response.data?.accessToken) as string,
        isActive: (response.data?.status === 'active' || response.data?.isActive) as boolean,
        startTime: (response.data?.created_at || response.data?.startTime) as string,
        replicaId: (response.data?.replica_id || response.data?.replicaId) as string,
        personaId: (response.data?.persona_id || response.data?.personaId) as string,
        error: response.data?.error as string | undefined,
      };
 
      return conversationResponse;
    } catch (error) {
      Iif (error && typeof error === 'object' && 'type' in error) {
        throw error;
      }
 
      const tavusError = this.createError(error, 'network', {
        operation: 'getConversation',
        conversationId,
      });
 
      Iif (this.debug) {
        console.error('Error getting conversation:', tavusError);
      }
 
      throw tavusError;
    }
  }
 
  /**
   * End a conversation
   */
  async endConversation(conversationId: string): Promise<void> {
    try {
      Iif (!this.isInitialized) {
        throw new Error('TavusClient must be initialized before ending conversations');
      }
 
      Iif (!conversationId || typeof conversationId !== 'string') {
        const error = this.createError(
          new Error('Conversation ID is required and must be a string'),
          'validation',
          { operation: 'endConversation', conversationId }
        );
        throw error;
      }
 
      Iif (this.debug) {
        console.log('Ending conversation:', { conversationId });
      }
 
      const response = await this.makeRequest(`/conversations/${conversationId}`, {
        method: 'DELETE',
      });
 
      Iif (!response.success) {
        const error = this.createError(
          new Error(response.error || 'Failed to end conversation'),
          'server',
          {
            operation: 'endConversation',
            conversationId,
            statusCode: response.statusCode,
          }
        );
        throw error;
      }
 
      Iif (this.debug) {
        console.log('Conversation ended successfully:', { conversationId });
      }
 
      // Clean up the timer if conversation was manually ended
      this.cleanupConversationTimer(conversationId);
    } catch (error) {
      Iif (error && typeof error === 'object' && 'type' in error) {
        throw error;
      }
 
      const tavusError = this.createError(error, 'network', {
        operation: 'endConversation',
        conversationId,
      });
 
      Iif (this.debug) {
        console.error('Error ending conversation:', tavusError);
      }
 
      throw tavusError;
    }
  }
 
  /**
   * Set up automatic conversation ending timer
   */
  private setupConversationTimer(
    conversation: ConversationResponse, 
    properties: Record<string, unknown>
  ): void {
    const conversationId = conversation.conversationId;
    const maxDuration = (properties.max_call_duration as number) || 30; // Default 30 seconds
    
    Iif (this.debug) {
      console.log(`Setting up auto-end timer for conversation ${conversationId}: ${maxDuration} seconds`);
    }
 
    // Store conversation info
    this.activeConversations.set(conversationId, {
      startTime: new Date(),
      maxDuration
    });
 
    // Set up timer to automatically end the conversation
    const timer = setTimeout(async () => {
      try {
        Iif (this.debug) {
          console.log(`Auto-ending conversation ${conversationId} after ${maxDuration} seconds`);
        }
        
        await this.endConversation(conversationId);
        this.cleanupConversationTimer(conversationId);
      } catch (error) {
        Iif (this.debug) {
          console.error(`Failed to auto-end conversation ${conversationId}:`, error);
        }
      }
    }, maxDuration * 1000); // Convert seconds to milliseconds
 
    this.conversationTimers.set(conversationId, timer);
  }
 
  /**
   * Clean up conversation timer and tracking
   */
  private cleanupConversationTimer(conversationId: string): void {
    const timer = this.conversationTimers.get(conversationId);
    Iif (timer) {
      clearTimeout(timer);
      this.conversationTimers.delete(conversationId);
    }
    this.activeConversations.delete(conversationId);
    
    Iif (this.debug) {
      console.log(`Cleaned up timer for conversation ${conversationId}`);
    }
  }
 
  /**
   * Get active conversation count for monitoring
   */
  public getActiveConversationCount(): number {
    return this.activeConversations.size;
  }
 
  /**
   * Get remaining time for a conversation
   */
  public getConversationRemainingTime(conversationId: string): number {
    const conversation = this.activeConversations.get(conversationId);
    Iif (!conversation) {
      return 0;
    }
 
    const elapsed = (Date.now() - conversation.startTime.getTime()) / 1000;
    const remaining = Math.max(0, conversation.maxDuration - elapsed);
    return Math.floor(remaining);
  }
 
  /**
   * Stop video streaming session
   */
  async stopVideoStream(sessionId: string): Promise<void> {
    Iif (!this.isInitialized) {
      throw new Error('TavusClient must be initialized before stopping video streams');
    }
 
    try {
      const response = await this.makeRequest(`/sessions/${sessionId}/stream`, {
        method: 'DELETE',
      });
 
      Iif (!response.success) {
        throw new Error(response.error || 'Failed to stop video stream');
      }
    } catch (error) {
      Iif (this.debug) {
        console.error('Error stopping video stream:', error);
      }
      throw error;
    }
  }
 
  /**
   * Get session status and details
   */
  async getSession(sessionId: string): Promise<TavusSession> {
    Iif (!this.isInitialized) {
      throw new Error('TavusClient must be initialized before getting session details');
    }
 
    try {
      const response = await this.makeRequest(`/sessions/${sessionId}`, {
        method: 'GET',
      });
 
      Iif (!response.success) {
        throw new Error(response.error || 'Failed to get session details');
      }
 
      return response.data as unknown as TavusSession;
    } catch (error) {
      Iif (this.debug) {
        console.error('Error getting session details:', error);
      }
      throw error;
    }
  }
 
  /**
   * End a video session
   */
  async endSession(sessionId: string): Promise<void> {
    Iif (!this.isInitialized) {
      throw new Error('TavusClient must be initialized before ending sessions');
    }
 
    try {
      const response = await this.makeRequest(`/sessions/${sessionId}`, {
        method: 'DELETE',
      });
 
      Iif (!response.success) {
        throw new Error(response.error || 'Failed to end session');
      }
    } catch (error) {
      Iif (this.debug) {
        console.error('Error ending session:', error);
      }
      throw error;
    }
  }
 
  /**
   * Get available personas
   */
  async getPersonas(): Promise<PersonaConfig[]> {
    Iif (!this.isInitialized) {
      throw new Error('TavusClient must be initialized before fetching personas');
    }
 
    try {
      const response = await this.makeRequest('/personas', {
        method: 'GET',
      });
 
      Iif (!response.success) {
        throw new Error(response.error || 'Failed to fetch personas');
      }
 
      return (response.data?.personas || []) as PersonaConfig[];
    } catch (error) {
      Iif (this.debug) {
        console.error('Error fetching personas:', error);
      }
      throw error;
    }
  }
 
  /**
   * Create a new persona
   */
  async createPersona(config: Omit<PersonaConfig, 'personaId'>): Promise<PersonaConfig> {
    Iif (!this.isInitialized) {
      throw new Error('TavusClient must be initialized before creating personas');
    }
 
    try {
      const response = await this.makeRequest('/personas', {
        method: 'POST',
        body: {
          name: config.name,
          description: config.description,
          prompt_template: config.promptTemplate,
          language: config.language,
          voice_engine: config.voiceEngine,
          pipeline_mode: config.pipelineMode,
        },
      });
 
      Iif (!response.success) {
        throw new Error(response.error || 'Failed to create persona');
      }
 
      return response.data as unknown as PersonaConfig;
    } catch (error) {
      Iif (this.debug) {
        console.error('Error creating persona:', error);
      }
      throw error;
    }
  }
 
  /**
   * Get session transcript
   */
  async getSessionTranscript(sessionId: string): Promise<string> {
    Iif (!this.isInitialized) {
      throw new Error('TavusClient must be initialized before getting transcripts');
    }
 
    try {
      const response = await this.makeRequest(`/sessions/${sessionId}/transcript`, {
        method: 'GET',
      });
 
      Iif (!response.success) {
        throw new Error(response.error || 'Failed to get session transcript');
      }
 
      return (response.data?.transcript || '') as string;
    } catch (error) {
      Iif (this.debug) {
        console.error('Error getting session transcript:', error);
      }
      throw error;
    }
  }
 
  /**
   * Get session recording URL
   */
  async getSessionRecording(sessionId: string): Promise<string> {
    Iif (!this.isInitialized) {
      throw new Error('TavusClient must be initialized before getting recordings');
    }
 
    try {
      const response = await this.makeRequest(`/sessions/${sessionId}/recording`, {
        method: 'GET',
      });
 
      Iif (!response.success) {
        throw new Error(response.error || 'Failed to get session recording');
      }
 
      return (response.data?.recording_url || '') as string;
    } catch (error) {
      Iif (this.debug) {
        console.error('Error getting session recording:', error);
      }
      throw error;
    }
  }
 
  /**
   * Get existing conversations for cleanup
   */
  async getConversations(): Promise<ConversationResponse[]> {
    try {
      Iif (!this.isInitialized) {
        throw new Error('TavusClient must be initialized before getting conversations');
      }
 
      Iif (this.debug) {
        console.log('Getting existing conversations...');
      }
 
      const response = await this.makeRequest('/conversations', {
        method: 'GET',
      });
 
      Iif (!response.success) {
        const error = this.createError(
          new Error(response.error || 'Failed to get conversations'),
          'server',
          {
            operation: 'getConversations',
            statusCode: response.statusCode,
          }
        );
        throw error;
      }
 
      Iif (this.debug) {
        console.log('Conversations retrieved successfully:', response.data);
      }
 
      // Map the response to our interface
      const conversations = (response.data?.conversations || []) as TavusConversationObject[];
      return conversations.map((conv: TavusConversationObject) => ({
        conversationId: (conv.conversation_id || conv.conversationId)!,
        roomUrl: (conv.conversation_url || conv.roomUrl)!,
        accessToken: (conv.access_token || conv.accessToken)!,
        isActive: (conv.status === 'active' || conv.isActive)!,
        startTime: (conv.created_at || conv.startTime)!,
        replicaId: (conv.replica_id || conv.replicaId)!,
        personaId: (conv.persona_id || conv.personaId)!,
        error: conv.error,
      }));
    } catch (error) {
      // If it's already a TavusError, re-throw it
      Iif (error && typeof error === 'object' && 'type' in error) {
        throw error;
      }
 
      const tavusError = this.createError(error, 'network', {
        operation: 'getConversations',
      });
 
      Iif (this.debug) {
        console.error('Error getting conversations:', tavusError);
      }
 
      throw tavusError;
    }
  }
 
  /**
   * Connect to WebRTC room and get video stream from Tavus conversation
   */
  async connectToWebRTCRoom(roomUrl: string, accessToken?: string): Promise<MediaStream> {
    try {
      Iif (!this.isInitialized) {
        throw new Error('TavusClient must be initialized before connecting to WebRTC room');
      }
 
      Iif (!roomUrl || typeof roomUrl !== 'string') {
        throw new Error('Room URL is required for WebRTC connection');
      }
 
      Iif (this.debug) {
        console.log('Connecting to Tavus room using Daily.js:', { roomUrl, hasAccessToken: !!accessToken });
      }
 
      // Load Daily.js from CDN if not already loaded
      Iif (typeof window !== 'undefined' && !window.Daily) {
        const script = document.createElement('script');
        script.src = 'https://unpkg.com/@daily-co/daily-js';
        script.crossOrigin = 'anonymous';
        document.head.appendChild(script);
        
        // Wait for Daily.js to load
        await new Promise<void>((resolve, reject) => {
          script.onload = () => resolve();
          script.onerror = () => reject(new Error('Failed to load Daily.js'));
        });
      }
 
      // Create Daily call frame
      const callFrame = window.Daily.createFrame({
        showLeaveButton: false,
        showFullscreenButton: false,
        showLocalVideo: false,
        showParticipantsBar: false,
        iframeStyle: {
          width: '100%',
          height: '100%',
          border: '0px',
          borderRadius: '8px',
        },
      });
 
      // Set up event handlers
      callFrame.on('joining-meeting', (): void => {
        Iif (this.debug) {
          console.log('Joining Tavus meeting...');
        }
      });
 
      callFrame.on('joined-meeting', (): void => {
        Iif (this.debug) {
          console.log('Successfully joined Tavus meeting');
        }
      });
 
      callFrame.on('participant-joined', (event): void => {
        Iif (this.debug) {
          console.log('Participant joined:', event.participant);
        }
      });
 
      callFrame.on('participant-updated', (event): void => {
        Iif (this.debug) {
          console.log('Participant updated:', event.participant);
        }
      });
 
      callFrame.on('error', (event) => {
        console.error('Daily call error:', event);
        throw new Error(`Daily call error: ${event.errorMsg || 'Unknown error'}`);
      });
 
      // Join the room
      await callFrame.join({ url: roomUrl });
 
      // Wait for the meeting to be fully joined
      await new Promise<void>((resolve, reject) => {
        const timeout = setTimeout(() => {
          reject(new Error('Timeout waiting for meeting to join'));
        }, 10000);
 
        callFrame.on('joined-meeting', () => {
          clearTimeout(timeout);
          resolve();
        });
 
        callFrame.on('error', (event) => {
          clearTimeout(timeout);
          reject(new Error(`Failed to join meeting: ${event.errorMsg}`));
        });
      });
 
      // Get the video stream from the Daily call
      const participants = callFrame.participants();
      const remoteParticipants = Object.values(participants).filter(
        (participant) => participant.owner && participant.video
      );
 
      Iif (remoteParticipants.length === 0) {
        throw new Error('No remote video participants found in Tavus room');
      }
 
      // Get the first remote participant's video stream
      const remoteParticipant = remoteParticipants[0];
      Iif (!remoteParticipant) {
        throw new Error('No remote participants found in Tavus room');
      }
      const videoTrack = remoteParticipant.videoTrack;
 
      Iif (!videoTrack) {
        throw new Error('No video track available from remote participant');
      }
 
      // Create a MediaStream from the video track
      const stream = new MediaStream([videoTrack]);
 
      Iif (this.debug) {
        console.log('Successfully connected to Tavus video stream via Daily.js');
      }
 
      return stream;
 
    } catch (error) {
      Iif (this.debug) {
        console.error('Error connecting to WebRTC room:', error);
      }
      
      // No fallbacks - just throw the error
      throw error;
    }
  }
 
  /**
   * Determine call type from API endpoint
   */
  private getCallTypeFromEndpoint(endpoint: string): string {
    if (endpoint.includes('/conversations') && endpoint.includes('POST')) {
      return 'create_conversation';
    } else if (endpoint.includes('/conversations') && endpoint.includes('GET')) {
      return 'get_conversation';
    } else if (endpoint.includes('/conversations') && endpoint.includes('DELETE')) {
      return 'end_conversation';
    } else if (endpoint.includes('/replicas')) {
      return 'get_replicas';
    } else if (endpoint.includes('/personas')) {
      return 'get_personas';
    } else if (endpoint.includes('/sessions')) {
      return 'video_stream';
    } else {
      return 'default';
    }
  }
}