"""
Enhanced help system with topic-specific guidance.
"""

import typer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text

console = Console()
app = typer.Typer(help="Enhanced help and documentation")


HELP_TOPICS = {
    "pipeline": {
        "title": "Pipeline System",
        "description": "Learn about the 6-stage pipeline system for generating billing data",
        "content": """
The CloudZero Billing Generator uses a 6-stage pipeline system:

1. **generate**: Create base usage data from reference files (Required)
   - Variance patterns are now integrated into the generate stage
2. **k8s**: Apply Kubernetes-based cost allocation (Optional)
3. **metadata**: Apply product/customer/team metadata allocation (Optional)
4. **usage**: Calculate usage amounts for telemetry (Optional)
5. **discount**: Apply discounts and credits (Optional)
6. **tax**: Calculate taxes and fees (Optional)

**Common Commands:**
• czbillgen pipeline run full <org>        - Run complete pipeline
• czbillgen pipeline stage k8s <org>       - Run specific stage
• czbillgen pipeline validate config <org> - Validate configuration
        """,
        "examples": [
            "czbillgen pipeline run full my-org",
            "czbillgen pipeline stage metadata my-org --verbose",
            "czbillgen pipeline validate config my-org",
        ],
    },
    "telemetry": {
        "title": "Telemetry Data Generation",
        "description": "Generate data for CloudZero platform APIs",
        "content": """
The telemetry system generates synthetic data for CloudZero APIs:

**Unit Metrics Telemetry:**
- Custom business metrics (users, transactions, API calls)
- Used for unit cost analysis and anomaly detection
- Generated monthly with realistic patterns

**Allocation Telemetry:**
- Usage-based shared cost allocation data
- Defines how shared costs are distributed
- Supports multiple allocation methods

**Common Commands:**
• czbillgen telemetry unit-metrics generate <org>
• czbillgen telemetry allocation generate <org>
• czbillgen telemetry unit-metrics validate <org>
        """,
        "examples": [
            "czbillgen telemetry unit-metrics generate my-org",
            "czbillgen telemetry allocation generate my-org --verbose",
            "czbillgen telemetry unit-metrics validate my-org",
        ],
    },
    "profiles": {
        "title": "Profile Pattern System",
        "description": "Manage behavioral patterns for realistic data generation",
        "content": """
The unified profile system provides behavioral patterns:

**Pattern Types:**
• **Growth**: Linear, exponential, logistic growth patterns
• **Seasonality**: Weekly, monthly, quarterly patterns
• **Anomaly**: Spikes, dips, step changes
• **Distribution**: Balanced, skewed, Pareto distributions

**Pattern Categories:**
• Business (steady growth, seasonal peaks)
• Technology (scaling, outages, deployments)
• Finance (month-end spikes, budget cycles)
• Operations (maintenance windows, capacity planning)

**Common Commands:**
• czbillgen profiles list all
• czbillgen profiles list types
• czbillgen profiles show <pattern-name>
• czbillgen profiles validate all
        """,
        "examples": [
            "czbillgen profiles list all --type=growth",
            "czbillgen profiles show steady_exponential_growth",
            "czbillgen profiles validate all",
        ],
    },
    "reference": {
        "title": "Reference Data Management",
        "description": "Manage and validate cloud service reference data",
        "content": """
Reference data defines cloud services and their properties:

**Required Columns:**
• cloud_provider: AWS, Azure, GCP, etc.
• service: EC2, Storage, Compute, etc.
• usage_family: Compute, Storage, Network, etc.
• resource_type: Instance, Volume, LoadBalancer, etc.
• operation: RunInstances, GetObject, etc.
• usage_type: BoxUsage, StorageUsage, etc.
• instance_type: t3.micro, Standard_D2s_v3, etc.

**Validation Features:**
• Schema validation
• Column name normalization
• Duplicate detection
• Cloud provider validation

**Common Commands:**
• czbillgen reference validate file data/reference.csv
• czbillgen reference usage analyze data/reference.csv
• czbillgen reference usage providers data/reference.csv
        """,
        "examples": [
            "czbillgen reference validate file data/providers.csv --fix",
            "czbillgen reference usage analyze data/providers.csv --provider=AWS",
            "czbillgen reference usage services data/providers.csv",
        ],
    },
    "getting-started": {
        "title": "Getting Started Guide",
        "description": "Quick start guide for new users",
        "content": """
**Quick Start Guide:**

1. **Initialize Organization:**
   czbillgen init my-org

2. **Prepare Reference Data:**
   czbillgen reference validate file data/providers.csv

3. **Configure Pipeline:**
   Edit my-org/billing/pipeline-configs/basic.pipeline.yaml with your settings

4. **Run Pipeline:**
   czbillgen pipeline run full my-org

5. **Generate Telemetry (Optional):**
   czbillgen telemetry unit-metrics generate my-org

6. **Upload Data:**
   czbillgen upload data my-org

**Directory Structure:**
cloudzero-demo-billing/
├── reference-data/       # Global reference data
└── orgs/
    └── my-org/
        ├── config.yaml           # Main configuration
        ├── billing/
        │   ├── configs/          # Pipeline settings
        │   │   └── main.yaml
        │   └── runs/            # Billing output data
        └── telemetry/
            ├── configs/          # Telemetry settings
            └── runs/            # Telemetry output data
        """,
        "examples": [
            "czbillgen init my-company",
            "czbillgen pipeline run full my-company --verbose",
            "czbillgen telemetry unit-metrics generate my-company",
        ],
    },
    "configuration": {
        "title": "Configuration Management",
        "description": "Understanding configuration files and settings",
        "content": """
**Configuration Files:**

**config.yaml** - Main organization settings:
• org_name: Organization identifier
• api_token: CloudZero API token
• api_url: CloudZero API endpoint (optional)

**billing/pipeline-configs/basic.pipeline.yaml** - Pipeline stage configuration:
• Defines which stages to run
• Stage-specific parameters
• Input/output file paths

**Telemetry Configs:**
• telemetry/configs/unit-metrics.yaml: Unit metrics definitions
• telemetry/configs/allocations.yaml: Allocation telemetry settings
• telemetry/configs/metadata.yaml: Product/customer mappings
• telemetry/configs/k8s.yaml: Kubernetes allocation rules

**Environment Variables:**
• CLOUDBILLGEN_<ORG>_API_TOKEN: API token per org
• ANTHROPIC_MODEL: Override model selection

**Common Commands:**
• czbillgen config validate my-org
• czbillgen config show my-org
        """,
        "examples": [
            "czbillgen config validate my-org",
            "czbillgen config show my-org --config=custom.yaml",
        ],
    },
}


@app.command()
def topics():
    """List all available help topics."""
    table = Table(title="Available Help Topics")
    table.add_column("Topic", style="cyan")
    table.add_column("Description", style="white")

    for topic, info in HELP_TOPICS.items():
        table.add_row(topic, info["description"])

    console.print(table)
    console.print(
        "\n[blue]Use 'czbillgen help topic <topic-name>' for detailed information[/blue]"
    )


@app.command()
def topic(topic_name: str = typer.Argument(..., help="Help topic name")):
    """Show detailed help for a specific topic."""
    if topic_name not in HELP_TOPICS:
        console.print(f"[red]Unknown help topic: {topic_name}[/red]")
        console.print(
            "[blue]Use 'czbillgen help topics' to see available topics[/blue]"
        )
        return

    topic_info = HELP_TOPICS[topic_name]

    # Create title panel
    title_text = Text(topic_info["title"], style="bold green")
    console.print(Panel(title_text, border_style="green"))

    # Show description
    console.print(f"\n{topic_info['description']}\n")

    # Show content
    console.print(topic_info["content"])

    # Show examples
    if "examples" in topic_info:
        console.print("\n[bold blue]Examples:[/bold blue]")
        for example in topic_info["examples"]:
            console.print(f"  [green]${example}[/green]")


@app.command()
def commands():
    """Show overview of all command groups."""
    command_groups = {
        "Core Operations": {
            "commands": [
                "czbillgen init <org>",
                "czbillgen config validate <org>",
                "czbillgen upload data <org>",
            ],
            "description": "Organization setup and data upload",
        },
        "Pipeline Operations": {
            "commands": [
                "czbillgen pipeline run full <org>",
                "czbillgen pipeline stage <stage> <org>",
                "czbillgen pipeline validate config <org>",
            ],
            "description": "6-stage billing data generation pipeline",
        },
        "Telemetry Generation": {
            "commands": [
                "czbillgen telemetry unit-metrics generate <org>",
                "czbillgen telemetry allocation generate <org>",
            ],
            "description": "Generate data for CloudZero APIs",
        },
        "Reference Data": {
            "commands": [
                "czbillgen reference validate file <file>",
                "czbillgen reference usage analyze <file>",
            ],
            "description": "Manage cloud service reference data",
        },
        "Profile Management": {
            "commands": [
                "czbillgen profiles list all",
                "czbillgen profiles show <pattern>",
                "czbillgen profiles validate all",
            ],
            "description": "Manage behavioral patterns",
        },
    }

    console.print("[bold green]CloudZero Billing Generator Commands[/bold green]\n")

    for group_name, group_info in command_groups.items():
        console.print(f"[bold blue]{group_name}[/bold blue]")
        console.print(f"  {group_info['description']}")
        console.print()

        for command in group_info["commands"]:
            console.print(f"  [green]{command}[/green]")
        console.print()


@app.command()
def workflow():
    """Show common workflow examples."""
    workflows = [
        {
            "name": "Basic Billing Data Generation",
            "steps": [
                "czbillgen init my-org",
                "# Edit my-org/pipeline.yaml with your settings",
                "czbillgen reference validate file data/providers.csv",
                "czbillgen pipeline run full my-org",
                "czbillgen upload data my-org",
            ],
        },
        {
            "name": "Generate Unit Metrics Telemetry",
            "steps": [
                "czbillgen init my-org",
                "# Create my-org/unit_metrics.yaml config",
                "czbillgen telemetry unit-metrics validate my-org",
                "czbillgen telemetry unit-metrics generate my-org",
            ],
        },
        {
            "name": "Debug Pipeline Issues",
            "steps": [
                "czbillgen config validate my-org",
                "czbillgen pipeline validate config my-org",
                "czbillgen reference validate file data/providers.csv",
                "czbillgen pipeline run full my-org --verbose",
            ],
        },
    ]

    console.print("[bold green]Common Workflows[/bold green]\n")

    for workflow in workflows:
        console.print(f"[bold blue]{workflow['name']}:[/bold blue]")
        for step in workflow["steps"]:
            if step.startswith("#"):
                console.print(f"  [yellow]{step}[/yellow]")
            else:
                console.print(f"  [green]{step}[/green]")
        console.print()


# Default command to show overview
@app.callback(invoke_without_command=True)
def help_overview(ctx: typer.Context):
    """Show help overview."""
    if ctx.invoked_subcommand is None:
        console.print("[bold green]CloudZero Billing Generator Help[/bold green]\n")
        console.print("Use the following commands to get help:")
        console.print(
            "  [green]czbillgen help topics[/green]    - List all help topics"
        )
        console.print(
            "  [green]czbillgen help commands[/green]  - Show command overview"
        )
        console.print(
            "  [green]czbillgen help workflow[/green]  - Show common workflows"
        )
        console.print(
            "  [green]czbillgen help topic <name>[/green] - Get detailed help on a topic"
        )
        console.print(
            "\nQuick start: [green]czbillgen help topic getting-started[/green]"
        )
