"""CLI for SRM."""

import argparse
import json
import sys
import time
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from srm import ResourceMonitor

console = Console()


def main():
    parser = argparse.ArgumentParser(prog="srm", description="Simple Resource Monitor")
    parser.add_argument("-w", "--watch", type=float, help="Continuous monitoring with interval")
    parser.add_argument("-t", "--top", type=int, default=5, help="Top processes to show")
    parser.add_argument("-j", "--json", action="store_true", help="JSON output")
    parser.add_argument("-v", "--version", action="version", version="%(prog)s 0.1.0")
    args = parser.parse_args()
    
    monitor = ResourceMonitor()
    
    if args.watch:
        try:
            while True:
                metrics = monitor.all_metrics(args.top)
                console.clear()
                display(metrics, args.top, args.json)
                time.sleep(args.watch)
        except KeyboardInterrupt:
            console.print("\n[dim]Stopped.[/]")
    else:
        display(monitor.all_metrics(args.top), args.top, args.json)


def display(metrics, top_count, json_out):
    if json_out:
        print(metrics.to_json())
        return
    
    # CPU
    cpu_lines = []
    for i, c in enumerate(metrics.cpu.per_core):
        bar = "█" * int(c/5) + "░" * (20-int(c/5))
        color = "red" if c > 80 else "yellow" if c > 60 else "green"
        cpu_lines.append(f"Core {i:2d}: [{color}]{bar}[/{color}] {c:5.1f}%")
    cpu_lines.append(f"\nOverall: {metrics.cpu.percent:.1f}%")
    console.print(Panel("\n".join(cpu_lines), title="CPU", border_style="blue"))
    
    # Memory
    mem = metrics.memory
    bar = "█" * int(mem.percent/5) + "░" * (20-int(mem.percent/5))
    color = "red" if mem.percent > 80 else "green"
    console.print(Panel(f"RAM: [{color}]{bar}[/{color}] {mem.percent:.1f}%\n{mem.used/(1024**3):.1f}/{mem.total/(1024**3):.1f} GB", title="Memory", border_style="magenta"))
    
    # Disk
    disk_lines = []
    for p in metrics.disk.partitions[:5]:
        color = "red" if p.percent > 80 else "green"
        disk_lines.append(f"[{color}]{p.mountpoint:15s}[/{color}] {p.percent:5.1f}% ({p.used/(1024**3):.1f}/{p.total/(1024**3):.1f} GB)")
    console.print(Panel("\n".join(disk_lines), title="Disk", border_style="yellow"))
    
    # Processes
    table = Table(title=f"Top {top_count} Processes")
    table.add_column("PID", justify="right")
    table.add_column("Name")
    table.add_column("CPU %", justify="right")
    table.add_column("MEM %", justify="right")
    for p in metrics.top_processes[:top_count]:
        table.add_row(str(p.pid), p.name[:20], f"{p.cpu_percent:.1f}", f"{p.memory_percent:.1f}")
    console.print(table)


if __name__ == "__main__":
    main()
