#!/usr/bin/env python3
"""Code generation script to create async_client.py from client.py.

This script automatically generates the async client code based on the sync client,
ensuring consistency between the two implementations.

Usage:
    python scripts/generate_async_client.py
"""
import re
import sys
from pathlib import Path


def main():
    script_dir = Path(__file__).parent
    project_root = script_dir.parent
    client_file = project_root / "traveltimepy" / "client.py"
    async_client_file = project_root / "traveltimepy" / "async_client.py"

    if not client_file.exists():
        print(f"Error: Source file {client_file} does not exist")
        sys.exit(1)

    with open(client_file, "r", encoding="utf-8") as f:
        content = f.read()

    async_client = generate_async_client(content)

    with open(async_client_file, "w", encoding="utf-8") as f:
        f.write(async_client)

    print(f"Generated {async_client_file}")


def generate_async_client(content: str) -> str:

    warning_header = """# AUTO-GENERATED FILE
# This file is automatically generated from client.py
# Do not edit this file directly. Run scripts/generate_async_client.py instead.

"""

    # 1. Update imports
    content = re.sub(
        r"from traveltimepy\.sync_base_client import SyncBaseClient",
        "from traveltimepy.async_base_client import AsyncBaseClient",
        content,
    )

    # 2. Change class name and inheritance
    content = re.sub(
        r"class Client\(SyncBaseClient\):",
        "class AsyncClient(AsyncBaseClient):",
        content,
    )

    # 3. Convert method definitions to async
    content = re.sub(r"(\s+)def (\w+)\(", r"\1async def \2(", content)

    # 4. Add await to API calls
    content = re.sub(
        r"(\s+)return (self\._api_call_(?:post|get|proto)\()",
        r"\1return await \2",
        content,
    )

    # 5. Add await to other async operations
    content = re.sub(
        r"(\s+)(res: \w+Response = )(self\._api_call_get\()", r"\1\2await \3", content
    )

    return warning_header + content


if __name__ == "__main__":
    main()
