#!/usr/bin/env python3
"""{{app_description}}"""

import click
import sys
import os
from pathlib import Path
from typing import Optional, List
from rich.console import Console
from rich.table import Table
{{#if config_file}}
{{#if (eq config_format "yaml")}}
import yaml
{{else if (eq config_format "json")}}
import json
{{else if (eq config_format "toml")}}
import toml
{{/if}}
{{/if}}

console = Console()

{{#if config_file}}
class Config:
    """Configuration loader"""

    def __init__(self, config_path: Optional[Path] = None):
        self.config_path = config_path or Path.home() / '.{{app_name}}' / 'config.{{config_format}}'
        self.data = self.load()

    def load(self) -> dict:
        """Load configuration from file"""
        if not self.config_path.exists():
            return {}

        with open(self.config_path, 'r') as f:
            {{#if (eq config_format "yaml")}}
            return yaml.safe_load(f) or {}
            {{else if (eq config_format "json")}}
            return json.load(f)
            {{else if (eq config_format "toml")}}
            return toml.load(f)
            {{/if}}

    def save(self):
        """Save configuration to file"""
        self.config_path.parent.mkdir(parents=True, exist_ok=True)
        with open(self.config_path, 'w') as f:
            {{#if (eq config_format "yaml")}}
            yaml.dump(self.data, f)
            {{else if (eq config_format "json")}}
            json.dump(self.data, f, indent=2)
            {{else if (eq config_format "toml")}}
            toml.dump(self.data, f)
            {{/if}}
{{/if}}

@click.group()
@click.version_option(version='{{app_version}}')
{{#if config_file}}
@click.option('-c', '--config', type=click.Path(exists=True), help='Config file path')
{{/if}}
@click.option('-v', '--verbose', count=True, help='Verbose output')
@click.pass_context
def cli(ctx, {{#if config_file}}config, {{/if}}verbose):
    """{{app_description}}"""
    ctx.ensure_object(dict)
    ctx.obj['verbose'] = verbose
    {{#if config_file}}
    ctx.obj['config'] = Config(Path(config) if config else None)
    {{/if}}

{{#each commands}}
@cli.command()
{{#each this.arguments}}
@click.argument('{{this.name}}'{{#if this.required}}, required=True{{/if}}{{#if this.type}}, type={{this.python_click_type}}{{/if}})
{{/each}}
{{#each this.options}}
@click.option('{{#if this.short}}-{{this.short}}, {{/if}}--{{this.long}}'{{#if this.help}}, help='{{this.help}}'{{/if}}{{#if this.default}}, default='{{this.default}}'{{/if}}{{#if this.multiple}}, multiple=True{{/if}}{{#if this.type}}, type={{this.python_click_type}}{{/if}})
{{/each}}
@click.pass_context
def {{snake_case this.name}}(
    ctx,
    {{#each this.arguments}}
    {{this.name}},
    {{/each}}
    {{#each this.options}}
    {{this.long}},
    {{/each}}
):
    """{{this.about}}"""
    try:
        verbose = ctx.obj['verbose']
        {{#if ../config_file}}
        config = ctx.obj['config']
        {{/if}}

        {{#each this.validators}}
        # Validate {{this.field}}
        {{#if (eq this.type "range")}}
        if {{this.field}} < {{this.min}} or {{this.field}} > {{this.max}}:
            raise click.BadParameter('{{this.error_message}}')
        {{else if (eq this.type "regex")}}
        import re
        if not re.match(r'{{this.pattern}}', str({{this.field}})):
            raise click.BadParameter('{{this.error_message}}')
        {{/if}}
        {{/each}}

        if verbose:
            console.print(f"[green]Executing {{this.name}} command[/green]")

        # TODO: Implement {{this.name}} command logic
        {{#each this.arguments}}
        console.print(f"  {{this.name}}: {{{this.name}}}")
        {{/each}}
        {{#each this.options}}
        if {{this.long}}:
            console.print(f"  {{this.long}}: {{{this.long}}}")
        {{/each}}

    except Exception as e:
        console.print(f"[red]Error:[/red] {str(e)}", style="bold red")
        sys.exit(1)

{{/each}}

if __name__ == '__main__':
    cli(obj={})
