"""
CLI commands for content operations.
"""

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


@click.command('content-get')
@click.option('--file', 'file_path', required=True, type=click.Path(exists=True),
              help='Path to markdown file')
def content_get(file_path):
    """Extract content without frontmatter and tailmatter."""
    try:
        file_path = Path(file_path)
        with open(file_path, 'r', encoding='utf-8') as f:
            text = f.read()

        parser = ContentParser()
        content = parser.extract_content(text)

        click.echo(content)

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


@click.command('content-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 content_stats(file_path, output_format):
    """Calculate content statistics."""
    try:
        file_path = Path(file_path)
        with open(file_path, 'r', encoding='utf-8') as f:
            text = f.read()

        parser = ContentParser()
        content = parser.extract_content(text)
        stats = parser.calculate_stats(content)

        if output_format == 'json':
            click.echo(json.dumps(stats.to_dict(), indent=2))
        else:
            click.echo(f"Word count: {stats.word_count}")
            click.echo(f"Line count: {stats.line_count}")
            click.echo(f"Paragraph count: {stats.paragraph_count}")
            click.echo(f"Character count: {stats.character_count}")

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