# Copyright (c) CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com
#

"""
CUR Validation Rules Management

Commands for viewing and managing CUR (Cost and Usage Report) validation rules
stored in DynamoDB backend.
"""

import sys

from rich import box
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

from src.api.v4_cur_rules import get_cur_validation_rules, reset_cur_validation_rules
from src.utils.console import confirm, eprint

console = Console()


def functions(arguments, _organization_data=None):
    """
    Handle CUR validation rules commands.

    Commands:
        czops config cur-rules list - Show current rules
        czops config cur-rules reset - Reset to defaults
    """
    debug = arguments.get("--debug", False)

    # Handle subcommands
    if arguments.get("list"):
        _display_cur_rules(debug)
    elif arguments.get("reset"):
        _reset_cur_rules(debug)
    else:
        # Default to list if no subcommand specified
        _display_cur_rules(debug)


def _display_cur_rules(debug: bool = False):
    """Display current CUR validation rules."""
    console.print("\n[bold cyan]CUR Validation Rules[/bold cyan]")
    console.print("[dim]These rules determine which CUR configurations are viable for CloudZero[/dim]\n")

    try:
        # Fetch rules from backend
        rule_set = get_cur_validation_rules(debug=debug)

        # Display rule set metadata
        metadata_table = Table(box=box.SIMPLE, show_header=False, padding=(0, 2))
        metadata_table.add_column("Property", style="dim")
        metadata_table.add_column("Value")

        metadata_table.add_row("Rule Set ID", rule_set.rule_set_id)
        metadata_table.add_row("Name", rule_set.rule_set_name)
        metadata_table.add_row("Version", rule_set.rule_set_version)
        metadata_table.add_row("Description", rule_set.description)
        metadata_table.add_row("Last Updated", rule_set.last_updated)
        metadata_table.add_row("Updated By", rule_set.updated_by or "system")

        console.print(metadata_table)
        console.print()

        # Display rules in a table
        rules_table = Table(
            title="Validation Rules",
            box=box.ROUNDED,
            show_header=True,
            header_style="bold cyan",
            padding=(0, 1),
        )

        rules_table.add_column("Rule ID", style="cyan", no_wrap=True)
        rules_table.add_column("Field", style="bright_white")
        rules_table.add_column("Level", justify="center", width=12)
        rules_table.add_column("Allowed Values", style="green")
        rules_table.add_column("Status", justify="center", width=8)

        for rule in rule_set.rules:
            # Determine level color
            level_color = "red" if rule.validation_level == "required" else "yellow"
            level_display = f"[{level_color} bold]{rule.validation_level.upper()}[/{level_color} bold]"

            # Determine status color
            status_color = "green" if rule.enabled else "dim"
            status_text = "✅ ON" if rule.enabled else "⚪ OFF"

            rules_table.add_row(
                rule.rule_id,
                rule.field_name,
                level_display,
                ", ".join(rule.allowed_values),
                f"[{status_color}]{status_text}[/{status_color}]",
            )

        console.print(rules_table)
        console.print()

        # Show legend
        legend_panel = Panel(
            "[green bold]YES[/green bold] = All required rules pass\n"
            "[yellow bold]WARN[/yellow bold] = Required rules pass, but recommended rules fail\n"
            "[red bold]NO[/red bold] = Required rules fail (CUR cannot be used)\n\n"
            "[red bold]REQUIRED[/red bold] = Must pass for CUR to be viable\n"
            "[yellow bold]RECOMMENDED[/yellow bold] = Should pass for optimal performance",
            title="[bold]Validation Levels[/bold]",
            border_style="cyan",
            box=box.ROUNDED,
        )
        console.print(legend_panel)
        console.print()

    except Exception as e:
        eprint(f"Error fetching CUR validation rules: {e}")
        if debug:
            console.print_exception()
        sys.exit(1)


def _reset_cur_rules(debug: bool = False):
    """Reset CUR validation rules to defaults."""
    console.print("\n[bold yellow]⚠️  Reset CUR Validation Rules[/bold yellow]")
    console.print("[dim]This will restore all rules to CloudZero defaults[/dim]\n")

    # Confirm action
    if not confirm("Are you sure you want to reset all CUR validation rules to defaults?"):
        console.print("[yellow]Reset cancelled[/yellow]")
        sys.exit(0)

    try:
        # Reset rules via API
        console.print("\n[cyan]Resetting rules to defaults...[/cyan]")
        rule_set = reset_cur_validation_rules(debug=debug)

        console.print(f"\n[bold green]✅ SUCCESS[/bold green] - Rules reset to defaults (version {rule_set.rule_set_version})\n")  # noqa: E501

        # Show confirmation
        console.print(f"[dim]Rule set:[/dim] {rule_set.rule_set_name}")
        console.print(f"[dim]Updated by:[/dim] {rule_set.updated_by}")
        console.print(f"[dim]Total rules:[/dim] {len(rule_set.rules)}")
        console.print()

        # Display the default rules
        _display_cur_rules(debug=False)

    except Exception as e:
        console.print("\n[bold red]❌ FAILED[/bold red] - Failed to reset rules\n")
        eprint(f"Error: {e}")
        if debug:
            console.print_exception()
        sys.exit(1)
