import argparse
import logging

from dataclasses import dataclass
from pathlib import Path

from saas.tools.devops.saas_disaster_alerts.disaster_alerts import create_or_update_alerts, DisasterAlertsConfig


@dataclass(frozen=True)
class Config(DisasterAlertsConfig):
    replace_remote: bool = False
    apply_remote: bool = False

    log_level: int = logging.INFO


def _parse_args() -> Config:
    parser: argparse.ArgumentParser = argparse.ArgumentParser()
    parser.add_argument('--owners', type=str, required=True, help='Alert owners separated by commas')
    parser.add_argument('--replace-remote', action='store_true',
                        help='Should replace remote alerts on generated ones or not')
    parser.add_argument('--apply-remote', action='store_true', help='Should apply generated alerts or not')

    parser.add_argument('--use-test-spi', action='store_true',
                        help='Should create alerts for all services or not, '
                             'incidents for services without disaster_alerts enabled will be in TESTSPI queue')
    parser.add_argument('--debug', action='store_true', help='Should show debug level logs or not')

    args: argparse.Namespace = parser.parse_args()
    if args.apply_remote and not args.replace_remote:
        raise ValueError('You should set --replace-remote if you want to generate and apply your alerts')

    return Config(
        owners=args.owners.split(','),
        jinja_templates_root_dir=Path(__file__).parent / 'templates',
        replace_remote=args.replace_remote,
        apply_remote=args.apply_remote,

        warden_use_test_spi=args.use_test_spi,
        log_level=logging.DEBUG if args.debug else logging.INFO
    )


def main() -> None:
    config: Config = _parse_args()
    logging.basicConfig(
        level=config.log_level,
        format='%(asctime)s | %(levelname)-7s | %(message)s',
        datefmt='%H:%M:%S',
        force=True
    )

    create_or_update_alerts(config, replace_remote=config.replace_remote, apply_remote=config.apply_remote)


if __name__ == '__main__':
    main()
