"""FileWriter - Atomic file write operations.

Contract: CNT-T3-ADP-006
"""

import os
import tempfile
from pathlib import Path

from laida_cli.adapters.file_system_adapter import FileSystemAdapter
from laida_cli.ports.file_system_port import FileSystemPort


class FileWriter:
    """Adapter for atomic file write operations.

    Uses temp file + rename pattern for atomic writes.
    """

    def __init__(self, fs_adapter: FileSystemPort | None = None) -> None:
        """Initialize file writer.

        Args:
            fs_adapter: File system port (uses default adapter if None)
        """
        self._fs: FileSystemPort = fs_adapter or FileSystemAdapter()

    def write_atomic(self, path: Path, content: str) -> None:
        """Write content atomically using temp file + rename.

        Args:
            path: Destination path
            content: Content to write
        """
        # Ensure parent directory exists
        self._fs.ensure_directory(path.parent)

        # Write to temp file first
        fd, temp_path = tempfile.mkstemp(
            dir=path.parent,
            prefix=".tmp_",
            suffix=path.suffix,
        )

        temp_file = Path(temp_path)
        try:
            # Write content and close fd immediately
            temp_file.write_text(content, encoding="utf-8")
            os.close(fd)  # Close fd right after write, before rename
            fd = -1  # Mark as closed

            # Atomic rename
            temp_file.rename(path)
        except Exception:
            # Close fd if still open
            if fd != -1:
                os.close(fd)
            # Clean up temp file on failure
            temp_file.unlink(missing_ok=True)
            raise

    def ensure_directory(self, path: Path) -> None:
        """Ensure directory exists.

        Args:
            path: Directory path
        """
        self._fs.ensure_directory(path)
