"""File system utilities for ASA CLI v2."""

import json
from pathlib import Path


def ensure_directory(path: Path) -> None:
    """Create directory and parents if they don't exist."""
    path.mkdir(parents=True, exist_ok=True)


def safe_read_file(path: Path) -> str:
    """Read file content as UTF-8 string.

    Args:
        path: Path to file.

    Returns:
        File content as string.

    Raises:
        FileNotFoundError: If file doesn't exist.
    """
    return path.read_text(encoding="utf-8")


def safe_write_file(path: Path, content: str, *, overwrite: bool = False) -> None:
    """Write content to file.

    Args:
        path: Target file path.
        content: Content to write.
        overwrite: If False and file exists, skip. If True, overwrite.
    """
    if path.exists() and not overwrite:
        return
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content, encoding="utf-8")


def safe_read_json(path: Path) -> dict:
    """Read and parse JSON file.

    Args:
        path: Path to JSON file.

    Returns:
        Parsed dictionary.

    Raises:
        FileNotFoundError: If file doesn't exist.
        json.JSONDecodeError: If JSON is invalid.
    """
    content = safe_read_file(path)
    return json.loads(content)


def safe_write_json(
    path: Path, data: dict, *, overwrite: bool = False, indent: int = 2
) -> None:
    """Write dictionary as JSON file.

    Args:
        path: Target file path.
        data: Dictionary to serialize.
        overwrite: If False and file exists, skip.
        indent: JSON indentation level.
    """
    content = json.dumps(data, indent=indent, ensure_ascii=False) + "\n"
    safe_write_file(path, content, overwrite=overwrite)


def merge_json_file(path: Path, updates: dict) -> None:
    """Read existing JSON, merge updates, write back.

    Used for package.json dependency merging during module install.

    Args:
        path: Path to JSON file.
        updates: Dictionary to deep-merge into existing data.
    """
    if path.exists():
        data = safe_read_json(path)
    else:
        data = {}

    _deep_merge(data, updates)
    safe_write_json(path, data, overwrite=True)


def _deep_merge(base: dict, updates: dict) -> None:
    """Recursively merge updates into base dict (in-place)."""
    for key, value in updates.items():
        if key in base and isinstance(base[key], dict) and isinstance(value, dict):
            _deep_merge(base[key], value)
        else:
            base[key] = value


def append_lines_to_file(path: Path, lines: list[str]) -> None:
    """Append lines to file, skipping duplicates.

    Used for .env.example updates.

    Args:
        path: Target file path.
        lines: Lines to append.
    """
    existing = set()
    if path.exists():
        existing = set(path.read_text(encoding="utf-8").splitlines())

    new_lines = [line for line in lines if line not in existing]
    if new_lines:
        with open(path, "a", encoding="utf-8") as f:
            for line in new_lines:
                f.write(line + "\n")
