"""OpenClaw Trading CLI."""
import os
from pathlib import Path
import typer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from openclaw.core.config import ConfigLoader, OpenClawConfig

app = typer.Typer(name='openclaw')
console = Console()

def _get_config_path():
    env_path = os.environ.get('OPENCLAW_CONFIG')
    if env_path:
        return Path(env_path)
    return None

@app.command()
def init(
    force: bool = typer.Option(False, '--force', '-f'),
    path: Path = typer.Option('openclaw.yaml', '--path', '-p'),
):
    """Initialize OpenClaw configuration."""
    console.print(Panel.fit('[bold blue]OpenClaw Initialization[/bold blue]'))
    if path.exists() and not force:
        console.print(f'[yellow]Config exists at {path}[/yellow]')
        raise typer.Exit(code=1)
    config_path = ConfigLoader.create_default_config(path)
    console.print(f'[green]Created config at {config_path}[/green]')

@app.command()
def run(
    mode: str = typer.Option('simulation', '--mode', '-m'),
    duration: int = typer.Option(30, '--duration', '-d'),
):
    """Run trading simulation."""
    console.print(Panel.fit('[bold blue]Trading Simulation[/bold blue]'))
    console.print(f'Mode: {mode}, Duration: {duration} days')

@app.command()
def status():
    """Show agent status."""
    console.print(Panel.fit('[bold blue]Agent Status[/bold blue]'))
    table = Table()
    table.add_column('Agent')
    table.add_column('Status')
    table.add_row('trader-001', 'stable')
    console.print(table)

# Config command group
config_app = typer.Typer(name='config', help='Configuration management')
app.add_typer(config_app)

@config_app.command('show')
def config_show():
    """Show current configuration."""
    config_path = _get_config_path()
    try:
        config = ConfigLoader.load(config_path) if config_path else ConfigLoader.load()
        console.print(Panel.fit('[bold blue]Configuration[/bold blue]'))
        console.print(f'Simulation days: {config.simulation_days}')
        console.print(f'Initial cash: {config.initial_cash}')
    except Exception as e:
        console.print(f'[red]Error: {e}[/red]')

@config_app.command('set')
def config_set(
    key: str = typer.Argument(..., help='Configuration key to set'),
    value: str = typer.Argument(..., help='Value to set'),
):
    """Set a configuration value."""
    console.print(f'[yellow]Setting {key} = {value}[/yellow]')
    console.print('[yellow]Note: Configuration update not yet implemented[/yellow]')

def main():
    app()

if __name__ == '__main__':
    main()