import os
import sys
import json

from mcp.server.fastmcp import FastMCP

from tencentcloud.common.common_client import CommonClient
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile

def get_env():
    secret_id = os.getenv("SECRET_ID")
    secret_key = os.getenv("SECRET_KEY")
    server_port = os.getenv("SERVER_PORT", "6675")

    return secret_id, secret_key, server_port


def req_create_migration_rag(secret_id: str, secret_key: str, ora_code: str, suffix: str, vendor: str):
    try:
        cred = credential.Credential(secret_id=secret_id, secret_key=secret_key)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "trtccopilot.tencentcloudapi.com"
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile

        params_json = {"Suffix": suffix, "Code": ora_code, "Vendor": vendor}
        params = json.dumps(params_json)

        common_client = CommonClient("trtccopilot", "2023-07-25", cred, "ap-guangzhou", profile=clientProfile)
        resp = common_client.call_json("CreateMigrationRag", json.loads(params))
        response = resp.get("Response", None)

        if response is not None:
            rag = response.get("RagText", None)
            if rag is not None:
                return rag
            else:
                error = response.get("Error", None)
                reqId = response.get("RequestId", None)
                errInfo = "Request failed."
                if error is not None:
                    errInfo += f" Error: {error}"
                if reqId is not None:
                    errInfo += f" RequestId: {reqId}"
                print(f"+> [Warn] CreateMigrationRag return error: {errInfo}")
                return errInfo
        else:
            return "response is None"
            
    except TencentCloudSDKException as err:
        print(f"+> [Warn] req CreateMigrationRag fail with: {err}")
        return f"request fail with err: {str(err)}"

def main():
    secret_id, secret_key, server_port = get_env()
    if secret_id is None or secret_key is None:
        print("+> [Error] secret_id or secret_key is null")
        sys.exit(-1)
    
    mcp = FastMCP(name="trtc-migration-assistant", json_response=True)

    @mcp.tool()
    def get_migration_doc(ora_code: str, suffix: str, vendor: str) -> str:
        """ Provide the latest API document, guidance and parameter specifications for migration from Agora or Zego to TRTC

        Args:
            ora_code: User code that integrates Agora or Zego
            suffix: Identify the programming language of the user_input_code and pass the corresponding file extension suffix. For example, the suffix for Objective-C is m, for Swift it's swift, for Java it's java, for Kotlin it's kt, and for Dart it's dart. If the language cannot be identified, prompt the user to provide the file extension suffix
            vendor: Which vendor? If specified by the user, pass Agora or Zego. If not specified, pass Undecided
        
        Returns:   
            str: migration guidence and re api document
        """
        # if vendor != "Agora" and vendor != "Zego":
        #     return f"vendor: {vendor} not support yet"
        
        resp = req_create_migration_rag(secret_id=secret_id, secret_key=secret_key, ora_code=ora_code, suffix=suffix, vendor=vendor)
        return resp
    
    mcp.add_tool(get_migration_doc)

    mcp.settings.host = "0.0.0.0"
    run_port = 6675
    try:
        run_port = int(server_port)
    except ValueError:
        print(f"+> [Error] can't convert server_port: {server_port} to int, use default port")
    mcp.settings.port = run_port
    mcp.run(transport="streamable-http")
    # mcp.run(transport="sse")
    
if __name__ == "__main__":
    main()
