import os

import typer
from google import genai
from rich.console import Console

console = Console()

# Module-level singleton — reuses HTTP connection pool across calls (faster)
_client = None


def _get_client():
    """Return the shared Gemini client, creating it once per process."""
    global _client
    if _client is None:
        api_key = os.environ.get("GEMINI_API_KEY")
        if not api_key:
            console.print(
                "[bold red]Error:[/bold red] GEMINI_API_KEY not set. "
                "Run [cyan]terrafy authenticate <api_key>[/cyan] first."
            )
            raise typer.Exit(code=1)
        # genai.Client manages an httpx session internally for connection reuse
        _client = genai.Client(api_key=api_key)
    return _client


def create(
    request: str = typer.Argument(
        help="Natural language description of infrastructure to create"
    ),
):
    """
    Generate production-ready HCL from a natural language request.
    """
    client = _get_client()

    # System prompt: ask Gemini to output filename on line 1, then "---", then HCL
    # This lets us derive a meaningful .tf filename from the resources being created
    system_prompt = (
        "You are an expert Terraform/HCL engineer. "
        "Respond in exactly this format:\n"
        "Line 1: a suitable snake_case filename with .tf extension based on the resources (e.g. s3_api_gateway.tf)\n"
        "Line 2: ---\n"
        "Remaining lines: production-ready HCL only, no markdown fences, no explanation."
    )

    with console.status("[bold green]Generating HCL...[/bold green]"):
        response = client.models.generate_content(
            model="gemini-2.5-flash",  # Fastest Gemini model
            contents=f"{system_prompt}\n\n{request}",
        )

    # Parse filename from first line, HCL from everything after the "---" separator
    lines = response.text.strip().splitlines()
    filename = lines[0].strip()
    hcl_content = "\n".join(lines[2:])  # skip filename line and "---"

    # Save HCL to file in the current working directory
    with open(filename, "w") as f:
        f.write(hcl_content)

    console.print(hcl_content)
    console.print(f"\n[bold green]Saved to:[/bold green] [cyan]{filename}[/cyan]")
