"""Replay runtime bootstrap."""

from __future__ import annotations

import json
from pathlib import Path

from autodebug_replay import (
    env_replay, file_replay, http_replay, network_guard,
    sql_replay, time_replay, redis_replay, aiohttp_replay,
    grpc_replay, boto3_replay, pymongo_replay,
    asyncpg_replay, aiomysql_replay, aiosqlite_replay,
    async_order_replay,
)
from autodebug_replay.transcripts import TranscriptIndex, load_transcripts

# Track installed guards for cleanup
_env_guard = None
_network_guard = None


def initialize(transcripts_dir: Path) -> TranscriptIndex:
    global _env_guard, _network_guard

    manifest = json.loads((transcripts_dir / "manifest.json").read_text(encoding="utf-8"))

    # Install env guard
    allowed_env = manifest.get("env_fingerprint", {}).get("env_vars_read", {})
    _env_guard = env_replay.EnvGuard(allowed_env)
    _env_guard.install()

    # Install network guard
    _network_guard = network_guard.NetworkGuard()
    _network_guard.install()

    # Install file replay guard (warn mode, not strict)
    captured_files = manifest.get("files_read", [])
    file_replay.install(captured_files, strict=False)

    # Load transcripts and install replay patches
    index = load_transcripts(transcripts_dir)
    time_replay.install(index)
    http_replay.install_requests(index)
    http_replay.install_httpx(index)
    sql_replay.install_psycopg2(index)
    sql_replay.install_psycopg(index)
    redis_replay.install(index)
    aiohttp_replay.install(index)
    grpc_replay.install(index)
    boto3_replay.install(index)
    pymongo_replay.install(index)
    asyncpg_replay.install_asyncpg(index)
    aiomysql_replay.install(index)
    aiosqlite_replay.install(index)

    # Install async task ordering enforcement (v2.0 bundles only)
    async_order_replay.install(index)

    return index


def uninstall_all() -> None:
    """Uninstall all replay patches, restoring original functions."""
    global _env_guard, _network_guard

    time_replay.uninstall()
    http_replay.uninstall()
    sql_replay.uninstall()
    redis_replay.uninstall()
    aiohttp_replay.uninstall()
    grpc_replay.uninstall()
    boto3_replay.uninstall()
    pymongo_replay.uninstall()
    asyncpg_replay.uninstall()
    aiomysql_replay.uninstall()
    aiosqlite_replay.uninstall()
    async_order_replay.uninstall()
    file_replay.uninstall()

    if _env_guard is not None:
        _env_guard.uninstall()
        _env_guard = None

    if _network_guard is not None:
        _network_guard.uninstall()
        _network_guard = None
