import argparse
import json
import os
import sys

# Attempt to use pyyaml if installed, otherwise fallback to json for basic parsing
try:
    import yaml
    HAS_YAML = True
except ImportError:
    HAS_YAML = False


def main():
    parser = argparse.ArgumentParser(description="DUADP — Decentralized Universal AI Discovery Protocol CLI")
    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    # Command: gen-gitlab
    gen_gitlab_parser = subparsers.add_parser("gen-gitlab", help="Generate GitLab AI Catalog YAML with injectGatewayToken")
    gen_gitlab_parser = subparsers.add_parser("gen-gitlab", help="Generate GitLab AI Catalog YAML with injectGatewayToken")

    # You can attach conformance and schema validation here in the future
    # conformance_parser = subparsers.add_parser("conformance")

    args = parser.parse_args()

    if args.command == "gen-gitlab":
        generate_gitlab(args.manifest)
    else:
        parser.print_help()


def generate_gitlab(manifest_path: str):
    if not os.path.exists(manifest_path):
        print(f"Error: File {manifest_path} does not exist.")
        sys.exit(1)

    print(f"Generating GitLab AI Catalog YAML from {manifest_path}...")

    resource = None
    with open(manifest_path, 'r', encoding='utf-8') as f:
        content = f.read()
        try:
            if manifest_path.endswith('.yaml') or manifest_path.endswith('.yml'):
                if HAS_YAML:
                    resource = yaml.safe_load(content)
                else:
                    print("Error: PyYAML is not installed. Please run `pip install pyyaml` to parse YAML manifests, or use JSON.")
                    sys.exit(1)
            else:
                resource = json.loads(content)
        except Exception as e:
            print(f"Error parsing {manifest_path}: {e}")
            sys.exit(1)

    if not resource:
        print(f"Error: Could not parse target manifest {manifest_path}.")
        sys.exit(1)

    metadata = resource.get('metadata', {})
    spec = resource.get('spec', {})

    agent_name = metadata.get('name', 'agent')
    description = metadata.get('description', 'External agent for GitLab Duo')

    runtime = spec.get('runtime', {})
    runtime_type = runtime.get('type', 'python')

    # Infer runtime defaults
    image = 'python:3.12-slim'
    commands = ['pip install --no-cache-dir -r requirements.txt', 'python main.py']

    if runtime_type in ['node', 'nodejs']:
        image = 'node:22-slim'
        commands = ['npm ci', 'npm run build', 'node dist/index.js']
    elif runtime_type in ['go', 'golang']:
        image = 'golang:1.22-alpine'
        commands = ['go build -o agent .', './agent']

    escaped_description = description.replace('"', '\\"')
    gitlab_yaml = [
        '# GitLab Duo External Agent Configuration',
        f'# Agent: {agent_name}',
        '# Generated by DUADP Python CLI',
        '',
        f'name: {agent_name}',
        f'description: "{escaped_description}"',
        '',
        '# Docker image for agent execution',
        f'image: {image}',
        '',
        '# Commands to execute agent',
        'commands:'
    ]

    for cmd in commands:
        gitlab_yaml.append(f'  - {cmd}')

    gitlab_yaml.extend([
        '',
        '# Default required variables',
        'variables:',
        '  - GITLAB_HOST',
        '  - GITLAB_TOKEN',
        '  - AI_FLOW_CONTEXT',
        '  - AI_FLOW_INPUT',
        '  - AI_FLOW_EVENT',
        '',
        '# Inject AI Gateway token for secure model access',
        'injectGatewayToken: true'
    ])

    llm = spec.get('llm')
    if llm:
        gitlab_yaml.extend([
            '',
            '# LLM configuration for AI Gateway',
            'llm:'
        ])
        if llm.get('provider'):
            gitlab_yaml.append(f"  provider: {llm['provider']}")
        if llm.get('model'):
            gitlab_yaml.append(f"  model: {llm['model']}")
        if llm.get('temperature') is not None:
            gitlab_yaml.append(f"  temperature: {llm['temperature']}")

    if runtime_type == 'webhook':
        gitlab_yaml.extend([
            '',
            '# Webhook runtime configuration',
            'runtime:',
            '  type: webhook'
        ])
        if runtime.get('port'):
            gitlab_yaml.append(f"  port: {runtime['port']}")
        if runtime.get('path'):
            gitlab_yaml.append(f"  path: {runtime['path']}")

    out_dir = os.path.abspath('.gitlab/agents')
    if not os.path.exists(out_dir):
        os.makedirs(out_dir, exist_ok=True)

    out_file = os.path.join(out_dir, f"{agent_name}.yaml")

    with open(out_file, 'w', encoding='utf-8') as fw:
        fw.write('\n'.join(gitlab_yaml))

    print(f"✓ GitLab Duo AI Catalog agent generated out successfully to:")
    print(f"  {out_file}")

if __name__ == "__main__":
    main()
