#
#   Imandra Inc.
#
#   codelogician/commands/test_cmd_sample.py
#

from __future__ import annotations

import json
import shutil
from pathlib import Path
from typing import Annotated, Any

import typer


def _emit_json(payload: dict[str, Any]) -> None:
    # JSON should be the only stdout output in --json mode
    typer.echo(json.dumps(payload, indent=2, sort_keys=True))


def run_sample_cmd(
    tgt_dir: Annotated[
        str, typer.Argument(help='Target directory where to place the sample project')
    ],
    json_flag: Annotated[
        bool,
        typer.Option(
            '--json',
            help='Emit machine-readable JSON to stdout (no rich output).',
        ),
    ] = False,
) -> None:
    """
    Create a sample project.
    """

    full_tgt_dir = Path(tgt_dir).expanduser().resolve()

    here = Path(__file__).resolve().parent  # .../src/codelogician/commands
    repo_root = here.parents[2]  # .../<repo-root>
    source_dir = (repo_root / 'data' / 'sample_bank_app').resolve()

    if not source_dir.exists():
        payload = {
            'ok': False,
            'error': 'SAMPLE_DATA_NOT_FOUND',
            'source_dir': str(source_dir),
            'target_dir': str(full_tgt_dir),
        }
        if json_flag:
            _emit_json(payload)
            raise typer.Exit(1)
        typer.secho(f'🛑 Sample data not found: {source_dir}', err=True)
        raise typer.Exit(1)

    if full_tgt_dir.exists():
        payload = {
            'ok': False,
            'error': 'TARGET_ALREADY_EXISTS',
            'source_dir': str(source_dir),
            'target_dir': str(full_tgt_dir),
        }
        if json_flag:
            _emit_json(payload)
            raise typer.Exit(2)
        typer.secho(f'⚠️ Target directory already exists: {full_tgt_dir}', err=True)
        raise typer.Exit(2)

    try:
        shutil.copytree(source_dir, full_tgt_dir)

        # Optional: useful metadata for callers
        copied_files = [
            str(p.relative_to(full_tgt_dir))
            for p in full_tgt_dir.rglob('*')
            if p.is_file()
        ]

        payload = {
            'ok': True,
            'source_dir': str(source_dir),
            'target_dir': str(full_tgt_dir),
            'files_copied': len(copied_files),
            'file_list': copied_files,
        }

        if json_flag:
            _emit_json(payload)
        else:
            typer.secho(f'✅ Created sample project in: {full_tgt_dir}')

    except Exception as e:
        payload = {
            'ok': False,
            'error': 'COPY_FAILED',
            'message': str(e),
            'source_dir': str(source_dir),
            'target_dir': str(full_tgt_dir),
        }
        if json_flag:
            _emit_json(payload)
        else:
            typer.secho(
                f'🛑 Failed to create sample project in {full_tgt_dir}: {e}',
                err=True,
            )
        raise typer.Exit(1)
