"""
Project commands (Stubbed/Thin).
"""
import click
import json
import sys
from rich.console import Console
from rich.table import Table
import httpx
from ..utils.auth import get_auth_token, API_BASE_URL

console = Console()

def get_client(token: str) -> httpx.Client:
    return httpx.Client(
        base_url=API_BASE_URL,
        headers={"Authorization": f"Bearer {token}"},
        timeout=30.0
    )

@click.group()
def projects():
    """Manage projects."""
    pass

@projects.command("list")
def list_projects():
    """List all projects."""
    token = get_auth_token()
    if not token:
        console.print("[red]Not logged in.[/red]")
        sys.exit(1)
        
    try:
        with get_client(token) as client:
            response = client.get("/projects/")
            if response.status_code == 200:
                data = response.json()
                table = Table(title="Projects")
                table.add_column("ID", style="cyan")
                table.add_column("Name", style="green")
                table.add_column("Created", style="dim")
                
                for p in data:
                    table.add_row(p.get("id"), p.get("name"), p.get("created_at", "")[:19])
                console.print(table)
            else:
                console.print(f"[red]Error: {response.status_code}[/red]")
    except Exception as e:
        console.print(f"[red]Connection error: {e}[/red]")

@projects.command("show")
@click.argument("project_id")
def show_project(project_id):
    """Show project details."""
    token = get_auth_token()
    if not token:
        sys.exit(1)
    
    with get_client(token) as client:
        response = client.get(f"/projects/{project_id}")
        if response.status_code == 200:
            console.print(json.dumps(response.json(), indent=2))
        else:
            console.print(f"[red]Error: {response.text}[/red]")

@projects.command("delete")
@click.argument("project_id")
def delete_project(project_id):
    """Delete a project."""
    token = get_auth_token()
    if not token:
        sys.exit(1)
        
    if click.confirm(f"Are you sure you want to delete project {project_id}?"):
        with get_client(token) as client:
            response = client.delete(f"/projects/{project_id}")
            if response.status_code == 204:
                console.print("[green]Project deleted.[/green]")
            else:
                console.print(f"[red]Failed: {response.text}[/red]")
