"""
Management command to ingest nginx log lines into the database.

Usage examples:

  # Read from a file
  python manage.py nginxmon_ingest --file /path/to/nginx.log

  # Pipe from stdin
  kubectl logs -n ingress-nginx deploy/ingress-nginx-controller | python manage.py nginxmon_ingest

  # Use the log file configured in NginxSettings
  python manage.py nginxmon_ingest --from-settings
"""
import sys

from django.core.management.base import BaseCommand

from nginxmon.fetcher import fetch_and_store, ingest_raw


class Command(BaseCommand):
    help = 'Ingest nginx ingress log lines into the nginxmon database'

    def add_arguments(self, parser):
        group = parser.add_mutually_exclusive_group()
        group.add_argument(
            '--file', '-f',
            metavar='PATH',
            help='Path to a nginx log file to ingest',
        )
        group.add_argument(
            '--from-settings',
            action='store_true',
            help='Run a full fetch using the source configured in NginxSettings '
                 '(kubectl or log file)',
        )
        # No flag = read from stdin

    def handle(self, *args, **options):
        if options['from_settings']:
            count = fetch_and_store()
            self.stdout.write(self.style.SUCCESS(f'Fetched and inserted {count} new log entries.'))
            return

        if options['file']:
            try:
                with open(options['file'], 'r', encoding='utf-8', errors='replace') as fh:
                    text = fh.read()
            except OSError as exc:
                self.stderr.write(self.style.ERROR(f'Cannot read file: {exc}'))
                return
        else:
            self.stdout.write('Reading from stdin… (Ctrl-D to finish)')
            text = sys.stdin.read()

        count = ingest_raw(text)
        self.stdout.write(self.style.SUCCESS(f'Inserted {count} new log entries.'))
