#!/usr/bin/env python3
"""
Generic ZXP to Boriel Basic Converter
Converts ZXP bitmap data to Boriel Basic DIM declarations.
"""

import argparse
import sys
import os
from tile_exporter import TileExporter

def read_zxp_file(filename):
    """Reads the .zxp file and extracts sprite lines and attribute lines."""
    try:
        with open(filename, 'r') as f:
            lines = f.readlines()
        
        sprite_lines = []
        attribute_lines = []
        parsing_attributes = False
        
        # Skip header (first 2 lines usually)
        # We start looking from line 2
        for line in lines[2:]:
            stripped = line.strip()
            if not stripped:
                # Empty line usually signals start of attributes if we have processed sprites
                if sprite_lines:
                    parsing_attributes = True
                continue
            
            if parsing_attributes:
                attribute_lines.append(stripped)
            else:
                # Filter for bitmap data (0s and 1s)
                # Some ZXP files might have other metadata, so we ensure it looks like bitmap
                if all(c in '01' for c in stripped):
                    sprite_lines.append(stripped)
                elif ' ' in stripped and all(c in '0123456789ABCDEFabcdef ' for c in stripped):
                     # Fallback: if we missed the blank line but see hex values
                     parsing_attributes = True
                     attribute_lines.append(stripped)

        return sprite_lines, attribute_lines
    except Exception as e:
        print(f"Error reading file {filename}: {e}")
        sys.exit(1)

# Sprite extraction and formatting helpers have been moved into TileExporter

def parse_attributes(attribute_lines):
    """Parses attribute lines into a single list of integer values."""
    attributes = []
    for line in attribute_lines:
        parts = line.split()
        for part in parts:
            try:
                attributes.append(int(part, 16))
            except ValueError:
                pass
    return attributes

# Sprite extraction and formatting helpers have been moved into TileExporter


def main():
    parser = argparse.ArgumentParser(description='Convert ZXP sprites to Boriel Basic.')
    parser.add_argument('--input', '-i', required=True, help='Input .zxp file')
    parser.add_argument('--width', '-w', type=int, required=True, help='Tile width (pixels)')
    parser.add_argument('--rows', '-r', type=int, required=True, help='Number of rows')
    parser.add_argument('--cols', '-c', type=int, required=True, help='Number of columns')
    parser.add_argument('--output', '-o', required=True, help='Output .bas file')
    parser.add_argument('--name', '-n', required=True, help='Variable name prefix')
    parser.add_argument('--no-attributes', action='store_true', help='Do not export attributes')
    parser.add_argument('--matrix', action='store_true', help='Return tiles and attributes as matrices (rows x cols x bytes)')
    
    args = parser.parse_args()
    
    if args.width % 8 != 0:
        print("Error: Width must be a multiple of 8.")
        sys.exit(1)
        
    sprite_lines, attribute_lines = read_zxp_file(args.input)
    attributes = parse_attributes(attribute_lines)
    
    # Calculate total size of one sprite in bytes
    total_bytes = (args.width // 8) * (args.width // 8) * 8
    # Array size is total_bytes - 1 (0-indexed)
    
    total_sprites = args.rows * args.cols
    
    # Infer total image width in pixels to help with attribute extraction
    # We assume the input rows/cols describe the layout in the file
    # But wait, args.rows and args.cols are usually passed by the user to define how many sprites to extract
    # However, to correctly extract attributes from the linear list, we need to know the 'stride' of the original image.
    # Usually ZXP exports the whole image width.
    # Let's try to infer it from the length of the first sprite line.
    
    if sprite_lines:
        image_width_px = len(sprite_lines[0])
    else:
        image_width_px = args.cols * args.width # Fallback
        
    
    with open(args.output, 'w') as f:
        f.write(f"' Generated by zxp2boriel.py\n")
        f.write(f"' Source: {os.path.basename(args.input)}\n")
        f.write(f"' Size: {args.width}x{args.width}\n")
        f.write(f"' Count: {total_sprites}\n\n")
        
        # Size of attributes per sprite = (W/8) * (W/8) bytes
        attr_bytes_per_sprite = (args.width // 8) * (args.width // 8)

        # total sprites counter (used for summary)
        count = total_sprites

        

        exporter = TileExporter(
            f, args, total_bytes, attr_bytes_per_sprite, image_width_px, attributes, sprite_lines, total_sprites
        )

        if args.matrix:
            exporter.write_matrix()
        else:
            exporter.write_flat()

        if not attributes and not args.no_attributes:
             f.write(f"' No attributes found in source file\n")
                
    print(f"Successfully generated {count} sprites in {args.output}")

if __name__ == '__main__':
    main()
