# Copyright (c) 2025 dev-droid. All rights reserved.
# Licensed under the MIT License. See LICENSE file in the project root for details.

import typer
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Confirm
from .llm import generate_cron
from .cron import validate_expression, get_next_schedule, add_job

app = typer.Typer(help="ai-cron: 自然语言转 Cron 表达式。")
console = Console()

@app.command()
def web(port: int = typer.Option(8080, help="Web server port")):
    """
    启动 Web 可视化界面。
    """
    from .web import start_web
    start_web(port=port)

@app.command()
def main(
    prompt: str = typer.Argument(..., help="自然语言描述的时间计划"),
    model: str = typer.Option("ollama/llama3", help="使用的模型 (默认: ollama/llama3)"),
    dry_run: bool = typer.Option(False, "--dry-run", help="仅显示结果，不写入 Crontab"),
):
    """
    将自然语言转换为 Cron 表达式。
    """
    with console.status(f"[bold green]思考中... (模型: {model})"):
        result = generate_cron(prompt, model=model)
    
    if "|" not in result:
        # Fallback or error handling
        if "ERROR" in result:
             console.print(f"[bold red]生成失败:[/bold red] {result}")
             raise typer.Exit(code=1)
        # Try to treat the whole string as expression validation if no pipe?
        # But our prompt enforces pipe. Let's assume error if no pipe.
        console.print(f"[bold red]非预期的输出格式:[/bold red] {result}")
        raise typer.Exit(code=1)

    expression, explanation = result.split("|", 1)
    expression = expression.strip()
    explanation = explanation.strip()

    # Validation
    is_valid = validate_expression(expression)
    
    if is_valid:
        console.print(Panel(f"[bold blue]{expression}[/bold blue]\n\n{explanation}", title="生成的 Cron 任务"))
        console.print("\n[bold]接下来几次运行时间:[/bold]")
        next_runs = get_next_schedule(expression)
        for run in next_runs:
            console.print(f"- {run}")
    else:
        console.print(f"[bold red]生成的表达式无效:[/bold red] {expression}")
        raise typer.Exit(code=1)

    if not dry_run:
        # Confirm with user
        if Confirm.ask("确认添加到 Crontab?"):
            # TODO: Get command from user input or prompt? 
            # The prompt is just "Every Friday at 5pm", we don't know the command!
            # We should probably ask for the command as an argument or interactively.
            # But the requirement says "One-Shot".
            # Let's ask interactively for the command if not provided.
            command_to_run = typer.prompt("请输入要运行的命令")
            
            success = add_job(expression, command_to_run, "Generated by ai-cron")
            if success:
                console.print("[bold green]成功添加到 Crontab![/bold green]")
            else:
                console.print("[bold red]写入 Crontab 失败。[/bold red]")
        else:
            console.print("[yellow]已取消。[/yellow]")
    else:
        console.print("\n[dim]Dry run 模式: 未做任何更改。[/dim]")

if __name__ == "__main__":
    app()
