#!/usr/bin/env python
"""
split_tga.py

Splits a TGA image into evenly sized 24-bit tiles. 
Reads parameters (TGA filename, rows, columns) from a .in file.

Usage:
    python split_tga.py tiles.in
"""

import sys
import os
import time
import datetime

try:
    from PIL import Image  # Pillow library
except ImportError:
    print("Error: The Pillow library is required (pip install Pillow).")
    sys.exit(1)

def main():
    # ----------------------------------------------------------------------
    # 1) Parse the Command-Line Argument
    # ----------------------------------------------------------------------
    if len(sys.argv) < 2:
        print("Usage: python split_tga.py <inputfile.in>")
        sys.exit(1)

    in_filename = sys.argv[1]

    # Check that it ends with .in
    if not in_filename.lower().endswith(".in"):
        print(f"Error: The input file '{in_filename}' must end with '.in'.")
        sys.exit(1)

    # ----------------------------------------------------------------------
    # 2) Read the .in File
    # ----------------------------------------------------------------------
    try:
        with open(in_filename, 'r', encoding="utf-8") as f:
            lines = f.readlines()
    except FileNotFoundError:
        print(f"Error: Input file '{in_filename}' not found.")
        sys.exit(1)

    # We only need the first three lines
    # Line 1: TGA path
    # Line 2: rows = X
    # Line 3: columns = Y
    if len(lines) < 3:
        print("Error: The .in file must have at least three lines.")
        sys.exit(1)

    tga_path = lines[0].strip()  # TGA filename
    rows_line = lines[1].strip()
    cols_line = lines[2].strip()

    # Parse the rows and columns lines ("rows = X" and "columns = Y")
    # A quick parse approach:
    try:
        # e.g. rows_line might be "rows = 10"
        #     splitting on '=' => ["rows ", " 10"]
        #     we just need the second part stripped -> "10"
        rows = int(rows_line.split('=')[1].strip())
        cols = int(cols_line.split('=')[1].strip())
    except Exception as e:
        print(f"Error reading rows/columns from lines:\n"
              f"  {rows_line}\n  {cols_line}\n"
              f"Details: {e}")
        sys.exit(1)

    # ----------------------------------------------------------------------
    # 3) Validate the TGA path and open the image
    # ----------------------------------------------------------------------
    if not tga_path.lower().endswith(".tga"):
        print(f"Error: The TGA file '{tga_path}' must end with '.tga'.")
        sys.exit(1)

    # Check existence
    if not os.path.isfile(tga_path):
        print(f"Error: TGA file '{tga_path}' does not exist.")
        sys.exit(1)

    # Open the TGA
    try:
        with Image.open(tga_path) as img:
            # Confirm it's 24-bit or 32-bit
            # Possible modes: "RGB", "RGBA", etc.
            if img.mode not in ("RGB", "RGBA"):
                print(f"Error: TGA file '{tga_path}' is not in an RGB-compatible mode. "
                      f"(mode={img.mode})")
                sys.exit(1)

            # If RGBA, convert to RGB (strip alpha)
            if img.mode == "RGBA":
                # This ensures the output will be 24-bit
                img = img.convert("RGB")

            width, height = img.size

            # ------------------------------------------------------------------
            # 4) Check for large width (prompt user if > 32768)
            # ------------------------------------------------------------------
            if width > 32768:
                response = input(f"The image width is {width}, which is > 32768. Proceed? (yes/no) ")
                if response.strip().lower() != "yes":
                    print("User declined to proceed with wide image.")
                    sys.exit(0)

            # We'll keep `img` open in memory for now.
            # We'll do the splitting below after setting up logs.

            # ------------------------------------------------------------------
            # 5) More checks: rows*cols, dimension divisibility
            # ------------------------------------------------------------------
            if rows * cols > 999:
                print(f"Error: rows x columns = {rows*cols}, which exceeds 999.")
                sys.exit(1)

            # Check even divisibility
            if (width % cols) != 0 or (height % rows) != 0:
                print("Error: The image cannot be evenly split into the specified "
                      f"{rows} rows and {cols} columns.\n"
                      f"Width {width} % cols {cols} = {width % cols}\n"
                      f"Height {height} % rows {rows} = {height % rows}")
                sys.exit(1)

            tile_width = width // cols
            tile_height = height // rows

            # ------------------------------------------------------------------
            # 6) Create a new Tiles-XXX folder
            # ------------------------------------------------------------------
            out_folder = None
            for i in range(1, 1000):
                candidate = f"Tiles-{i:03d}"
                if not os.path.exists(candidate):
                    out_folder = candidate
                    break

            if out_folder is None:
                print("Error: Could not find an available Tiles-XXX folder name up to 999.")
                sys.exit(1)

            os.mkdir(out_folder)

            # ------------------------------------------------------------------
            # 7) Set up logging (console + logging.txt)
            # ------------------------------------------------------------------
            log_path = os.path.join(out_folder, "logging.txt")
            log_file = open(log_path, "w", encoding="utf-8")

            def log(message):
                """Print to console and write to the log file."""
                print(message)
                log_file.write(message + "\n")
                log_file.flush()  # ensure logs are written promptly

            start_time = time.time()
            start_dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            log(f"--- Script started: {start_dt} ---")
            log(f"Input .in file    : {in_filename}")
            log(f"TGA file          : {tga_path}")
            log(f"Rows x Columns    : {rows} x {cols} = {rows*cols} tiles total")
            log(f"Output folder     : {out_folder}")
            log(f"Original TGA mode : {img.mode} (already converted to 'RGB' if RGBA was used)")
            log(f"Image size        : {width} x {height} pixels")
            log(f"Tile size         : {tile_width} x {tile_height} pixels (24-bit)")

            if width > 32768:
                log(f"User prompted about large width {width}, accepted to proceed.")

            log("Starting tile creation...")

            # ------------------------------------------------------------------
            # 8) Split image into tiles
            # ------------------------------------------------------------------
            tile_count = rows * cols

            # Coordinates in Pillow are (left, upper, right, lower).
            # row-major order: row 0..m-1, col 0..n-1
            tile_number = 0

            for row_idx in range(rows):
                for col_idx in range(cols):
                    tile_number += 1

                    left = col_idx * tile_width
                    upper = row_idx * tile_height
                    right = left + tile_width
                    lower = upper + tile_height

                    # Crop
                    tile = img.crop((left, upper, right, lower))

                    # Construct filename: Image_XXX.tga
                    out_name = f"Image_{tile_number:03d}.tga"
                    out_path = os.path.join(out_folder, out_name)

                    # Save as TGA (24-bit)
                    # By ensuring tile is in "RGB" mode, Pillow should save as 24-bit TGA.
                    tile = tile.convert("RGB")
                    tile.save(out_path, format="TGA")

                    log(f"Created tile {tile_number} of {tile_count} -> {out_name}")

            # ------------------------------------------------------------------
            # 9) Final logging (timestamp, elapsed time, etc.)
            # ------------------------------------------------------------------
            end_dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            elapsed_sec = time.time() - start_time
            elapsed_str = f"{elapsed_sec:.2f} seconds"

            log(f"--- All tiles created successfully. ---")
            log(f"Total tiles  : {tile_count}")
            log(f"Tile format  : RGB, 24-bit (no alpha)")
            log(f"Script ended : {end_dt}")
            log(f"Elapsed time : {elapsed_str}")

            log_file.close()

    except Exception as e:
        print(f"Unexpected error while processing TGA file '{tga_path}': {e}")
        sys.exit(1)

# If you want to allow running this script directly,
# include a typical Python boilerplate:
if __name__ == "__main__":
    main()
