"""
llmpm init

Initialise a ``llmpm.json`` in the current directory.

``llmpm.json`` is the project-local manifest for llmpm, inspired by npm's
``package.json``.  It declares which models belong to a project and switches
all llmpm commands to *local* mode so models are stored in ``<project>/.llmpm/``
instead of the global ``~/.llmpm/``.

Example manifest:

    {
      "name": "my-ai-project",
      "description": "Fine-tuning pipeline",
      "dependencies": {
        "meta-llama/Llama-3.2-3B-Instruct": "*",
        "openai/whisper-base": "*"
      }
    }
"""

from __future__ import annotations

import json
from pathlib import Path

import click

from llmpm import display
from llmpm.core import context


@click.command("init")
@click.option("--yes", "-y", is_flag=True, help="Skip all prompts and use defaults.")
def init(yes: bool) -> None:
    """Initialise a llmpm.json in the current directory."""
    display.header("init")
    display.blank()

    target = Path.cwd() / "llmpm.json"

    if target.exists():
        display.warn("[bold]llmpm.json[/] already exists in this directory.")
        display.info(
            "Run  [bold cyan]llmpm install <repo>[/]  to add a model, or edit "
            "[bold]llmpm.json[/] directly."
        )
        display.blank()
        raise SystemExit(0)

    default_name = Path.cwd().name

    if yes:
        name        = default_name
        description = ""
    else:
        name        = click.prompt("  package name", default=default_name)
        description = click.prompt("  description",  default="")

    display.blank()

    data: dict = {
        "name":         name,
        "description":  description,
        "dependencies": {},
    }

    with open(target, "w", encoding="utf-8") as fh:
        json.dump(data, fh, indent=2)
        fh.write("\n")

    display.ok(f"Created [bold]llmpm.json[/]  [dim]{target}[/]")
    display.blank()

    local_home = context.get_home()
    display.info(
        f"Models for this project will be stored in  "
        f"[dim]{local_home}[/]\n\n"
        f"  Add a model:  [bold cyan]llmpm install <repo>[/]\n"
        f"  Install all:  [bold cyan]llmpm install[/]"
    )
    display.blank()
