# curl_exporter.py
#
# Copyright 2025 Pavel Baksy
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: GPL-3.0-or-later

import shlex
from .base_exporter import BaseExporter
from ..models import HttpRequest


class CurlExporter(BaseExporter):
    """Export HTTP requests as cURL commands."""

    @property
    def format_name(self) -> str:
        return "cURL"

    @property
    def file_extension(self) -> str:
        return "sh"

    def export(self, request: HttpRequest) -> str:
        """
        Generate cURL command with proper shell escaping.

        Format:
        curl -X POST \
          'https://api.example.com/endpoint' \
          -H 'Content-Type: application/json' \
          --data '{"key": "value"}'
        """
        parts = ["curl"]

        # Add HTTP method (skip if GET - it's default)
        if request.method != "GET":
            parts.append(f"-X {request.method}")

        # Add URL (always quoted for safety)
        parts.append(shlex.quote(request.url))

        # Add headers
        for key, value in request.headers.items():
            header_str = f"{key}: {value}"
            parts.append(f"-H {shlex.quote(header_str)}")

        # Add body for POST/PUT/PATCH/DELETE methods
        if request.body and request.method in ["POST", "PUT", "PATCH", "DELETE"]:
            parts.append(f"--data {shlex.quote(request.body)}")

        # Format as multiline with backslash continuations
        return " \\\n  ".join(parts)


# Auto-register on import
from .registry import ExporterRegistry
ExporterRegistry.register('curl', CurlExporter)
