"""
koci Export Controller

Exports koci pipelines to other CI platform formats.
"""

import os
from pathlib import Path
from cement import Controller, ex

from ..core import parse_pipeline, ParserError, ValidationError
from ..output import OutputFormatter, Verbosity


class Export(Controller):
    """Controller for the 'export' command."""

    class Meta:
        label = 'export'
        stacked_on = 'base'
        stacked_type = 'nested'
        description = 'Export pipeline to other CI platforms'
        help = 'Convert koci.yml to GitHub Actions, Jenkins, etc.'

        arguments = [
            (['-f', '--file'],
             {'help': 'Path to koci.yml file',
              'action': 'store',
              'dest': 'file',
              'default': None}),

            (['-o', '--output'],
             {'help': 'Output file/directory',
              'action': 'store',
              'dest': 'output',
              'default': None}),

            (['--dry-run'],
             {'help': 'Print output without writing files',
              'action': 'store_true',
              'dest': 'dry_run',
              'default': False}),
        ]

    @ex(
        help='Export to GitHub Actions',
        arguments=[
            (['--workflow-name'],
             {'help': 'Workflow file name',
              'action': 'store',
              'dest': 'workflow_name',
              'default': 'ci.yml'}),
        ],
    )
    def github_actions(self):
        """Export to GitHub Actions format."""
        formatter = OutputFormatter(verbosity=Verbosity.NORMAL)

        try:
            pipeline = parse_pipeline(
                filepath=self.app.pargs.file,
                directory=os.getcwd(),
            )
        except (ParserError, ValidationError) as e:
            formatter.error(str(e))
            self.app.exit_code = 1
            return

        # Import exporter
        from ..exporters.github_actions import GitHubActionsExporter

        exporter = GitHubActionsExporter()
        output = exporter.export(pipeline)

        if self.app.pargs.dry_run:
            print(output)
            # Print secrets instructions if any
            instructions = exporter.get_secrets_setup_instructions()
            if instructions:
                print(instructions)
            return

        # Determine output path
        output_dir = Path(self.app.pargs.output or '.github/workflows')
        output_dir.mkdir(parents=True, exist_ok=True)

        output_file = output_dir / self.app.pargs.workflow_name
        output_file.write_text(output)

        formatter.success(f"Exported to {output_file}")

        # Print secrets instructions if any
        instructions = exporter.get_secrets_setup_instructions()
        if instructions:
            print(instructions)

    @ex(
        help='Export to Jenkins (Jenkinsfile)',
        arguments=[
            (['--declarative'],
             {'help': 'Use declarative pipeline syntax',
              'action': 'store_true',
              'dest': 'declarative',
              'default': True}),
        ],
    )
    def jenkins(self):
        """Export to Jenkinsfile format."""
        formatter = OutputFormatter(verbosity=Verbosity.NORMAL)

        try:
            pipeline = parse_pipeline(
                filepath=self.app.pargs.file,
                directory=os.getcwd(),
            )
        except (ParserError, ValidationError) as e:
            formatter.error(str(e))
            self.app.exit_code = 1
            return

        # Import exporter
        from ..exporters.jenkins import JenkinsExporter

        exporter = JenkinsExporter(declarative=self.app.pargs.declarative)
        output = exporter.export(pipeline)

        if self.app.pargs.dry_run:
            print(output)
            # Print secrets instructions if any
            instructions = exporter.get_secrets_setup_instructions()
            if instructions:
                print(instructions)
            return

        # Determine output path
        output_file = Path(self.app.pargs.output or 'Jenkinsfile')
        output_file.write_text(output)

        formatter.success(f"Exported to {output_file}")

        # Print secrets instructions if any
        instructions = exporter.get_secrets_setup_instructions()
        if instructions:
            print(instructions)

    @ex(
        help='Export to Jenkins with Kubernetes plugin',
        arguments=[
            (['--namespace'],
             {'help': 'Kubernetes namespace for pods',
              'action': 'store',
              'dest': 'namespace',
              'default': 'jenkins'}),
            (['--service-account'],
             {'help': 'Kubernetes service account',
              'action': 'store',
              'dest': 'service_account',
              'default': 'jenkins'}),
            (['--memory'],
             {'help': 'Default memory limit (e.g., 512Mi)',
              'action': 'store',
              'dest': 'memory',
              'default': '512Mi'}),
            (['--cpu'],
             {'help': 'Default CPU limit (e.g., 500m)',
              'action': 'store',
              'dest': 'cpu',
              'default': '500m'}),
        ],
    )
    def jenkins_k8s(self):
        """Export to Jenkinsfile format with Kubernetes plugin."""
        formatter = OutputFormatter(verbosity=Verbosity.NORMAL)

        try:
            pipeline = parse_pipeline(
                filepath=self.app.pargs.file,
                directory=os.getcwd(),
            )
        except (ParserError, ValidationError) as e:
            formatter.error(str(e))
            self.app.exit_code = 1
            return

        # Import exporter
        from ..exporters.jenkins_k8s import JenkinsK8sExporter

        exporter = JenkinsK8sExporter(
            namespace=self.app.pargs.namespace,
            service_account=self.app.pargs.service_account,
            default_memory=self.app.pargs.memory,
            default_cpu=self.app.pargs.cpu,
        )
        output = exporter.export(pipeline)

        if self.app.pargs.dry_run:
            print(output)
            # Print secrets instructions if any
            instructions = exporter.get_secrets_setup_instructions()
            if instructions:
                print(instructions)
            return

        # Determine output path
        output_file = Path(self.app.pargs.output or 'Jenkinsfile')
        output_file.write_text(output)

        formatter.success(f"Exported to {output_file}")

        # Print secrets instructions if any
        instructions = exporter.get_secrets_setup_instructions()
        if instructions:
            print(instructions)

    @ex(
        help='Export to GitLab CI',
    )
    def gitlab(self):
        """Export to GitLab CI format."""
        formatter = OutputFormatter(verbosity=Verbosity.NORMAL)

        try:
            pipeline = parse_pipeline(
                filepath=self.app.pargs.file,
                directory=os.getcwd(),
            )
        except (ParserError, ValidationError) as e:
            formatter.error(str(e))
            self.app.exit_code = 1
            return

        # Import exporter
        from ..exporters.gitlab import GitLabExporter

        exporter = GitLabExporter()
        output = exporter.export(pipeline)

        if self.app.pargs.dry_run:
            print(output)
            # Print secrets instructions if any
            instructions = exporter.get_secrets_setup_instructions()
            if instructions:
                print(instructions)
            return

        # Determine output path
        output_file = Path(self.app.pargs.output or '.gitlab-ci.yml')
        output_file.write_text(output)

        formatter.success(f"Exported to {output_file}")

        # Print secrets instructions if any
        instructions = exporter.get_secrets_setup_instructions()
        if instructions:
            print(instructions)

    @ex(
        help='Export to CircleCI',
        arguments=[
            (['--version'],
             {'help': 'CircleCI config version',
              'action': 'store',
              'dest': 'version',
              'default': '2.1'}),
        ],
    )
    def circleci(self):
        """Export to CircleCI format."""
        formatter = OutputFormatter(verbosity=Verbosity.NORMAL)

        try:
            pipeline = parse_pipeline(
                filepath=self.app.pargs.file,
                directory=os.getcwd(),
            )
        except (ParserError, ValidationError) as e:
            formatter.error(str(e))
            self.app.exit_code = 1
            return

        # Import exporter
        from ..exporters.circleci import CircleCIExporter

        exporter = CircleCIExporter(version=self.app.pargs.version)
        output = exporter.export(pipeline)

        if self.app.pargs.dry_run:
            print(output)
            # Print secrets instructions if any
            instructions = exporter.get_secrets_setup_instructions()
            if instructions:
                print(instructions)
            return

        # Determine output path
        output_dir = Path(self.app.pargs.output or '.circleci')
        output_dir.mkdir(parents=True, exist_ok=True)

        output_file = output_dir / 'config.yml'
        output_file.write_text(output)

        formatter.success(f"Exported to {output_file}")

        # Print secrets instructions if any
        instructions = exporter.get_secrets_setup_instructions()
        if instructions:
            print(instructions)

    @ex(
        help='Export to Concourse CI',
        arguments=[
            (['--git-resource'],
             {'help': 'Name for the git resource',
              'action': 'store',
              'dest': 'git_resource',
              'default': 'source-code'}),
        ],
    )
    def concourse(self):
        """Export to Concourse CI format."""
        formatter = OutputFormatter(verbosity=Verbosity.NORMAL)

        try:
            pipeline = parse_pipeline(
                filepath=self.app.pargs.file,
                directory=os.getcwd(),
            )
        except (ParserError, ValidationError) as e:
            formatter.error(str(e))
            self.app.exit_code = 1
            return

        # Import exporter
        from ..exporters.concourse import ConcourseExporter

        exporter = ConcourseExporter(git_resource=self.app.pargs.git_resource)
        output = exporter.export(pipeline)

        if self.app.pargs.dry_run:
            print(output)
            # Print secrets instructions if any
            instructions = exporter.get_secrets_setup_instructions()
            if instructions:
                print(instructions)
            return

        # Determine output path
        output_file = Path(self.app.pargs.output or 'pipeline.yml')
        output_file.write_text(output)

        formatter.success(f"Exported to {output_file}")

        # Print secrets instructions if any
        instructions = exporter.get_secrets_setup_instructions()
        if instructions:
            print(instructions)

    @ex(help='List supported export targets')
    def list(self):
        """List all supported export targets."""
        print("Supported export targets:")
        print("  github-actions  - GitHub Actions workflow (.github/workflows/)")
        print("  jenkins         - Jenkinsfile (Docker-based)")
        print("  jenkins-k8s     - Jenkinsfile (Kubernetes plugin)")
        print("  gitlab          - GitLab CI (.gitlab-ci.yml)")
        print("  circleci        - CircleCI (.circleci/config.yml)")
        print("  concourse       - Concourse CI (pipeline.yml)")
        print("\nUsage: koci export <target>")
