"""
CLI commands for contentmatter operations.
"""

import click
import json
from pathlib import Path
from .parser import ContentmatterParser


@click.command('contentmatter-get')
@click.argument('key')
@click.option('--file', 'file_path', required=True, type=click.Path(exists=True),
              help='Path to markdown file')
def contentmatter_get(key, file_path):
    """Get specific contentmatter value by key (MultiMarkdown key-value pairs)."""
    try:
        file_path = Path(file_path)
        with open(file_path, 'r', encoding='utf-8') as f:
            text = f.read()

        parser = ContentmatterParser()
        value = parser.get_contentmatter_value(text, key)

        if value is None:
            click.echo(f"Key '{key}' not found in contentmatter", err=True)
            return

        click.echo(value)

    except Exception as e:
        click.echo(f"Error: {e}", err=True)
        raise click.ClickException(f"Failed to get contentmatter value from {file_path}")


@click.command('contentmatter-set')
@click.argument('key_value')
@click.option('--file', 'file_path', required=True, type=click.Path(exists=True),
              help='Path to markdown file')
@click.option('--backup', is_flag=True, help='Create backup of original file')
def contentmatter_set(key_value, file_path, backup):
    """Set contentmatter value (format: key=value, adds MultiMarkdown key-value pair)."""
    try:
        if '=' not in key_value:
            raise click.ClickException("Key-value must be in format 'key=value'")

        key, value = key_value.split('=', 1)
        key = key.strip()
        value = value.strip()

        file_path = Path(file_path)

        # Create backup if requested
        if backup:
            backup_path = file_path.with_suffix(f"{file_path.suffix}.bak")
            backup_path.write_text(file_path.read_text())
            click.echo(f"Backup created: {backup_path}")

        with open(file_path, 'r', encoding='utf-8') as f:
            text = f.read()

        parser = ContentmatterParser()
        new_text = parser.set_contentmatter_value(text, key, value)

        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(new_text)

        click.echo(f"Set {key}={value} in contentmatter for {file_path}")

    except Exception as e:
        click.echo(f"Error: {e}", err=True)
        raise click.ClickException(f"Failed to set contentmatter value in {file_path}")


@click.command('contentmatter-keys')
@click.option('--file', 'file_path', required=True, type=click.Path(exists=True),
              help='Path to markdown file')
@click.option('--format', 'output_format', default='list', type=click.Choice(['list', 'json']),
              help='Output format (list or json)')
def contentmatter_keys(file_path, output_format):
    """List all contentmatter keys (MultiMarkdown key-value pairs)."""
    try:
        file_path = Path(file_path)
        with open(file_path, 'r', encoding='utf-8') as f:
            text = f.read()

        parser = ContentmatterParser()
        keys = parser.get_contentmatter_keys(text)

        if not keys:
            click.echo("No contentmatter keys found")
            return

        if output_format == 'json':
            click.echo(json.dumps(keys, indent=2))
        else:
            for key in sorted(keys):
                click.echo(key)

    except Exception as e:
        click.echo(f"Error: {e}", err=True)
        raise click.ClickException(f"Failed to list contentmatter keys from {file_path}")


@click.command('contentmatter-stats')
@click.option('--file', 'file_path', required=True, type=click.Path(exists=True),
              help='Path to markdown file')
@click.option('--format', 'output_format', default='json', type=click.Choice(['json', 'text']),
              help='Output format (json or text)')
def contentmatter_stats(file_path, output_format):
    """Calculate contentmatter statistics (MultiMarkdown key-value pairs)."""
    try:
        file_path = Path(file_path)
        with open(file_path, 'r', encoding='utf-8') as f:
            text = f.read()

        parser = ContentmatterParser()
        stats = parser.calculate_contentmatter_stats(text)

        if output_format == 'json':
            click.echo(json.dumps(stats.to_dict(), indent=2))
        else:
            click.echo(f"Has contentmatter: {stats.has_contentmatter}")
            click.echo(f"Total pairs: {stats.total_pairs}")
            click.echo(f"Average key length: {stats.average_key_length:.1f}")
            click.echo(f"Average value length: {stats.average_value_length:.1f}")
            click.echo(f"URL values: {stats.url_values}")
            click.echo(f"Email values: {stats.email_values}")
            click.echo(f"Date values: {stats.date_values}")

    except Exception as e:
        click.echo(f"Error: {e}", err=True)
        raise click.ClickException(f"Failed to calculate contentmatter stats for {file_path}")