"""venvy status — show project state."""
from __future__ import annotations
import os, subprocess
from pathlib import Path

from venvy.core import config as cfg_mod
from venvy.core.venv_manager import find, get_python
from venvy.core.injector import is_injected
from venvy.core.requirements import parse
from venvy.utils.console import console


def run() -> None:
    cwd = Path.cwd()
    root = cfg_mod.find_root(cwd)
    cfg = cfg_mod.load(root) if root else None

    console.print("\n[bold cyan]venvy status[/bold cyan]")
    console.print("─" * 42)

    if root:
        console.print(f"  Project root  : [bold]{root}[/bold]")
        console.print(f"  Venv name     : [bold]{cfg.venv_name}[/bold]")
        console.print(f"  Req file      : [bold]{cfg.req_file}[/bold]")
    else:
        console.print("  [dim]Not initialized — run [bold]venvy create venv[/bold][/dim]")

    active = os.environ.get("VIRTUAL_ENV")
    if active:
        venv = Path(active)
        console.print(f"  Active venv   : [green bold]{venv}[/green bold]")
        console.print(f"  Tracker       : {'[green]✓ installed[/green]' if is_injected(venv) else '[yellow]not installed (run venvy inject)[/yellow]'}")
        py = get_python(venv)
        if py.exists():
            r = subprocess.run([str(py), "--version"], capture_output=True, text=True)
            console.print(f"  Python        : [bold]{(r.stdout or r.stderr).strip()}[/bold]")
    else:
        venv = find(root or cwd)
        if venv:
            console.print(f"  Found venv    : [yellow]{venv}[/yellow] [dim](not active)[/dim]")
            console.print(f"  Tracker       : {'[green]✓ installed[/green]' if is_injected(venv) else '[yellow]not installed[/yellow]'}")
        else:
            console.print("  Venv          : [red]none found[/red]")

    # Show requirements
    req_name = cfg.req_file if cfg else "requirements.txt"
    req_file = (root or cwd) / req_name
    pkgs = parse(req_file)
    console.print(f"\n  [bold]{req_name}[/bold] ({len(pkgs)} packages)")
    for entry in sorted(pkgs.values()):
        console.print(f"    [cyan]•[/cyan] {entry}")
    console.print()
