# DO NOT EDIT: This file is auto-generated by the EigenCompute CLI
# Any changes made to this file will be overwritten when the project is regenerated

from typing import Any, Optional, Union
import uvicorn
from fastapi import FastAPI, Response, HTTPException
from pydantic import BaseModel
from openrpc import RPCServer
from eth_pydantic_types.hex.int import HexInt
from jsonrpcobjects.objects import (
    ErrorResponse,
    Notification,
    ParamsNotification,
    ParamsRequest,
    Request,
    ResultResponse,
)
import json
from pathlib import Path
from abc import ABC, abstractmethod

{{#has_types}}
from .types import *
{{/has_types}}

# Define the Union type for incoming RPC requests
RequestType = Union[ParamsRequest, Request, ParamsNotification, Notification]

class {{title}}Server(ABC):
    """Abstract base class for {{title}} server implementation"""
    
    {{#methods}}
    @abstractmethod
    async def {{snake_case_name}}(
        self,
        {{#params}}
        {{name}}: {{python_type}},
        {{/params}}
    ) -> {{result_type}}:
        """
        {{summary}}
        """
        pass
    
    {{/methods}}

# Load the ABI and OpenRPC schema from files
def _load_abi_data() -> Any:
    """Load ABI data from the generated JSON file"""
    abi_path = Path(__file__).parent / "{{abi_file}}"
    with abi_path.open("r") as f:
        return json.load(f)

def _load_openrpc_data() -> Any:
    """Load OpenRPC schema from the generated JSON file"""
    openrpc_path = Path(__file__).parent / "{{openrpc_spec_file}}"
    with openrpc_path.open("r") as f:
        return json.load(f)

ABI_DATA = _load_abi_data()
OPENRPC_DATA = _load_openrpc_data()

def ensure_hex_output(result):
    """Ensures the result is properly serialized to hex string."""
    if isinstance(result, int) and not isinstance(result, bool):
        return hex(result)
    elif isinstance(result, bool):
        return result
    elif isinstance(result, list):
        return [ensure_hex_output(item) for item in result]
    elif isinstance(result, dict):
        return {key: ensure_hex_output(value) for key, value in result.items()}
    elif isinstance(result, tuple):
        return tuple(ensure_hex_output(item) for item in result)
    return result

def create_rpc_server(server_impl: {{title}}Server) -> RPCServer:
    """Create and configure the RPC server with method implementations"""
    rpc = RPCServer(
        title="{{title}}",
        version="{{version}}",
        description="OpenRPC server for {{title}} API"
    )
    
    {{#methods}}
    # {{original_name}} method
    @rpc.method(name="compute_{{original_name}}")
    async def compute_{{snake_case_name}}(
        {{#params}}
        {{name}}: {{python_type}},
        {{/params}}
    ) -> {{result_type}}:
        """{{summary}}"""
        result = await server_impl.{{snake_case_name}}(
            {{#params}}
            {{name}},
            {{/params}}
        )
        return ensure_hex_output(result)
    
    {{/methods}}
    
    # system_health method for health checks
    @rpc.method()
    async def system_health() -> dict[str, str]:
        """Checks the health of the system."""
        return {"status": "ok"}
    
    # abi.discover method to serve the ABI
    @rpc.method(name='abi.discover')
    async def abi_discover() -> Any:
        """Returns the ABI for the smart contract associated with this API."""
        return ABI_DATA
    
    # rpc.discover method to serve the OpenRPC schema
    @rpc.method(name='rpc.discover')
    async def rpc_discover() -> Any:
        """Returns the OpenRPC schema for this API."""
        return OPENRPC_DATA
    
    return rpc

def create_fastapi_app(server_impl: {{title}}Server) -> FastAPI:
    """Create and configure the FastAPI application"""
    app = FastAPI(
        title="{{title}}",
        version="{{version}}",
        description="OpenRPC server for {{title}} API"
    )
    
    rpc = create_rpc_server(server_impl)
    
    # Custom HTTP endpoint to process RPC requests
    @app.post("/", response_model=Union[ErrorResponse, ResultResponse, None])
    async def http_process_rpc(request: RequestType) -> Response:
        """Process RPC request through HTTP server."""
        json_rpc_response = await rpc.process_request_async(request.json())
        return Response(content=json_rpc_response, media_type="application/json")
    
    return app

async def start_server(server_impl: {{title}}Server, port: int = {{server_port}}) -> None:
    """Start the server with the given implementation"""
    app = create_fastapi_app(server_impl)
    
    print(f"{{title}} Server started on http://0.0.0.0:{port}")
    
    config = uvicorn.Config(app, host="0.0.0.0", port=port)
    server = uvicorn.Server(config)
    await server.serve()
