# Copyright 2025 WhoMeta Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""uap CLI

Generated by WhoMeta Unified Agent Protocol SDK
"""
import json
from pathlib import Path
from typing import Optional

import typer

from unifiedagentprotocol.parser.openwebui import parse_openwebui  # type: ignore
from unifiedagentprotocol.parser.openapi import parse_openapi  # type: ignore
from unifiedagentprotocol.parser.swagger import parse_swagger  # type: ignore
from unifiedagentprotocol.export.to_mcp import agent_to_mcp  # type: ignore

app = typer.Typer(add_completion=False, help="Unified Agent Protocol CLI")


@app.command()
def bind(
    input: Path = typer.Option(..., exists=True, help="Input tool/agent definition file"),
    format: str = typer.Option("mcp", help="Target output format (mcp|a2a|openapi)"),
    output: Optional[Path] = typer.Option(None, help="Write result to file (defaults to stdout)"),
):
    """Convert an existing definition into a UAP export format."""

    data = json.loads(input.read_text())

    # OpenWebUI marketplace exports are wrapped in a list of objects that carry a
    # `tool` key. Accept such payloads by unwrapping the first element so that
    # the generic parser continues to work.
    if isinstance(data, list):
        if not data:
            typer.echo("Input list is empty – nothing to convert", err=True)
            raise typer.Exit(code=1)
        first = data[0]
        data = first.get("tool", first)

    # Basic format detection
    if isinstance(data, dict) and data.get("swagger", "")[:1] == "2":
        tool_or_agent = parse_swagger(data)
    elif isinstance(data, dict) and str(data.get("openapi", "")).startswith("3"):
        tool_or_agent = parse_openapi(data)[0] if isinstance(parse_openapi(data), list) else parse_openapi(data)
    else:
        tool_or_agent = parse_openwebui(data)

    if format == "mcp":
        result = agent_to_mcp(tool_or_agent)
    else:
        typer.echo("Unsupported format", err=True)
        raise typer.Exit(code=1)

    if output:
        output.write_text(json.dumps(result, indent=2))
    else:
        typer.echo(json.dumps(result, indent=2))


if __name__ == "__main__":
    app()
