# ============================
# line_renderer.py — Unit Cell & Utility Lines
# ============================
from __future__ import annotations
from OpenGL.GL import *
import numpy as np
from .shaders import LINE_VS, LINE_FS
from .utils import link_program

class LineRenderer:
    """Simple line renderer for unit cell boundaries and bonds."""
    def __init__(self):
        self.prog = link_program(LINE_VS, LINE_FS)
        self.vao = glGenVertexArrays(1)
        glBindVertexArray(self.vao)
        self.vbo = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, self.vbo)
        glEnableVertexAttribArray(0)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
        glBindVertexArray(0)

    def draw(self, view: np.ndarray, proj: np.ndarray, points: np.ndarray, 
             replica_count: int, rep_tbo: int, color: list = [1, 1, 1, 1]):
        if points.shape[0] == 0: return
        
        glUseProgram(self.prog)
        glUniformMatrix4fv(glGetUniformLocation(self.prog, "uView"), 1, GL_FALSE, view.T)
        glUniformMatrix4fv(glGetUniformLocation(self.prog, "uProj"), 1, GL_FALSE, proj.T)
        glUniform4f(glGetUniformLocation(self.prog, "uRGBA"), *color)
        
        glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_BUFFER, rep_tbo)
        glUniform1i(glGetUniformLocation(self.prog, "uReplicaOffsets"), 0)
        
        glBindVertexArray(self.vao)
        glBindBuffer(GL_ARRAY_BUFFER, self.vbo)
        glBufferData(GL_ARRAY_BUFFER, points.nbytes, points, GL_DYNAMIC_DRAW)
        
        glDrawArraysInstanced(GL_LINES, 0, points.shape[0], replica_count)
        glBindVertexArray(0)
