"""
koci Base Controller

Root controller with version banner and help.
"""

from cement import Controller, ex
from cement.utils.version import get_version_banner
from ..core.version import get_version

VERSION_BANNER = """
koci - Universal CI Definition Tool %s
%s

Run CI pipelines locally, export to any platform.
One CI file that grows with you.
""" % (get_version(), get_version_banner())


class Base(Controller):
    """Base controller for koci CLI."""

    class Meta:
        label = 'base'

        # Text displayed at the top of --help output
        description = 'koci - Universal CI Definition Tool'

        # Text displayed at the bottom of --help output
        epilog = '''
Commands:
  run         Execute pipeline locally
  validate    Validate pipeline file
  init        Create starter pipeline
  export      Export to other CI platforms
  watch       Watch and auto-run on changes
  visualize   Show pipeline structure

Examples:
  koci init                    Create koci.yml for your project
  koci validate                Check pipeline syntax
  koci run                     Run pipeline locally
  koci run --stage test        Run only test stage
  koci export github-actions   Export to GitHub Actions
  koci visualize               Show pipeline graph

Documentation: https://github.com/kodo/koci
'''

        # Controller level arguments
        arguments = [
            (['-v', '--version'],
             {'action': 'version',
              'version': VERSION_BANNER}),
        ]

    def _default(self):
        """Default action if no sub-command is passed."""
        self.app.args.print_help()

    @ex(
        help='Show pipeline summary',
        arguments=[
            (['-f', '--file'],
             {'help': 'Path to koci.yml file',
              'action': 'store',
              'dest': 'file',
              'default': None}),
        ],
    )
    def info(self):
        """Show information about the pipeline."""
        import os
        from ..core import parse_pipeline, ParserError, ValidationError
        from ..output import OutputFormatter, Verbosity

        formatter = OutputFormatter(verbosity=Verbosity.NORMAL)

        try:
            pipeline = parse_pipeline(
                filepath=self.app.pargs.file,
                directory=os.getcwd(),
            )

            print(f"\n📋 Pipeline: {pipeline.name}")
            print(f"   Version: {pipeline.version}")
            print(f"   Stages: {len(pipeline.stages)}")
            print(f"   Jobs: {len(pipeline.get_all_jobs())}")

            if pipeline.env:
                print(f"   Environment: {len(pipeline.env)} variables")

            print("\n   Structure:")
            for stage in pipeline.stages:
                print(f"   ├── {stage.name}")
                for job in stage.jobs:
                    extra = ""
                    if job.matrix:
                        extra = f" (×{len(job.matrix.expand())})"
                    print(f"   │   └── {job.name}{extra}")

            print()

        except (ParserError, ValidationError) as e:
            formatter.error(str(e))
            self.app.exit_code = 1

    @ex(
        help='List available stages',
        arguments=[
            (['-f', '--file'],
             {'help': 'Path to koci.yml file',
              'action': 'store',
              'dest': 'file',
              'default': None}),
        ],
    )
    def stages(self):
        """List all stages in the pipeline."""
        import os
        from ..core import parse_pipeline, ParserError, ValidationError

        try:
            pipeline = parse_pipeline(
                filepath=self.app.pargs.file,
                directory=os.getcwd(),
            )

            print("Stages:")
            for i, stage in enumerate(pipeline.stages, 1):
                job_count = len(stage.jobs)
                service_count = len(stage.services)

                extras = []
                if job_count:
                    extras.append(f"{job_count} jobs")
                if service_count:
                    extras.append(f"{service_count} services")

                extra_str = f" ({', '.join(extras)})" if extras else ""
                print(f"  {i}. {stage.name}{extra_str}")

        except (ParserError, ValidationError) as e:
            print(f"Error: {e}")
            self.app.exit_code = 1

    @ex(
        help='List all jobs',
        arguments=[
            (['-f', '--file'],
             {'help': 'Path to koci.yml file',
              'action': 'store',
              'dest': 'file',
              'default': None}),
            (['-s', '--stage'],
             {'help': 'Filter by stage',
              'action': 'store',
              'dest': 'stage',
              'default': None}),
        ],
    )
    def jobs(self):
        """List all jobs in the pipeline."""
        import os
        from ..core import parse_pipeline, ParserError, ValidationError

        try:
            pipeline = parse_pipeline(
                filepath=self.app.pargs.file,
                directory=os.getcwd(),
            )

            print("Jobs:")
            for stage in pipeline.stages:
                if self.app.pargs.stage and stage.name != self.app.pargs.stage:
                    continue

                print(f"\n  [{stage.name}]")
                for job in stage.jobs:
                    needs = f" ← {', '.join(job.needs)}" if job.needs else ""
                    matrix = f" (×{len(job.matrix.expand())})" if job.matrix else ""
                    print(f"    - {job.name}{needs}{matrix}")
                    print(f"      image: {job.image}")
                    print(f"      steps: {len(job.steps)}")

        except (ParserError, ValidationError) as e:
            print(f"Error: {e}")
            self.app.exit_code = 1
