import sys
import argparse
import numpy as np
import matplotlib.pyplot as plt

def parse_file1(filepath):
    try:
        with open(filepath, 'r') as f:
            content = f.read().split()
            
        if len(content) != 3:
            print(f"Error: input file ({filepath}) must contain exactly 3 integers.")
            sys.exit(1)
            
        integers = [int(x) for x in content]
        return integers[0] 
        
    except FileNotFoundError:
        print(f"Error: Could not find file '{filepath}'.")
        sys.exit(1)
    except ValueError:
        print(f"Error: {filepath} must contain integers only.")
        sys.exit(1)

def parse_file2(filepath):
    try:
        with open(filepath, 'r') as f:
            lines = [line.strip() for line in f.readlines()]
            
        while len(lines) < 2:
            lines.append("")
            
        list1 = [int(x) for x in lines[0].split()]
        list2 = [int(x) for x in lines[1].split()]
        
        return list1, list2
        
    except FileNotFoundError:
        print(f"Error: Could not find file '{filepath}'.")
        sys.exit(1)
    except ValueError:
        print(f"Error: output file ({filepath}) must contain only space-separated integers in its first two lines.")
        sys.exit(1)

def draw_grid(N, list1, list2, output_file="image.png"):
    fig, ax = plt.subplots(figsize=(8, 8))
    
    ax.set_xlim(-0.5, N - 0.5)
    ax.set_ylim(-0.5, N - 0.5)
    
    ax.invert_yaxis()
    
    ax.xaxis.tick_top()
    ax.xaxis.set_label_position('top')
    
    ax.set_xticks(np.arange(0, N, 1))
    ax.set_yticks(np.arange(0, N, 1))
    ax.set_xlabel('Columns (j)')
    ax.set_ylabel('Rows (i)')
    
    ax.set_xticks(np.arange(-0.5, N, 1), minor=True)
    ax.set_yticks(np.arange(-0.5, N, 1), minor=True)
    ax.grid(which='minor', color='black', linestyle='-', linewidth=1.5)
    ax.tick_params(which='minor', size=0) 
    
    x_vals = np.array([-0.5, N - 0.5])
    
    for k in list1:
        y_vals = k - x_vals
        ax.plot(x_vals, y_vals, color='green', linewidth=2.5, alpha=0.7)
        
    for k in list2:
        y_vals = x_vals + k
        ax.plot(x_vals, y_vals, color='blue', linewidth=2.5, alpha=0.7)

    plt.savefig(output_file, bbox_inches='tight', dpi=300)
    plt.close()
    print(f"Successfully generated '{output_file}' with an {N}x{N} grid.")

def main():
    parser = argparse.ArgumentParser(description="Visualizer for X")
    parser.add_argument("input_file", help="Path to the input file (must contain exactly 3 integers, first is N)")
    parser.add_argument("output_file", help="Path to the output file (first two lines contain lists of numbers)")
    
    args = parser.parse_args()
    
    N = parse_file1(args.input_file)
    
    if N <= 0:
        print("Error: N (the first integer in file 1) must be greater than 0.")
        sys.exit(1)
        
    C, D = parse_file2(args.output_file)
    
    draw_grid(N, C, D)

if __name__ == "__main__":
    main()
