import os
import sys
import cv2
import torch
from src.models.inference import SpindaInference
from src.utils.resolver import SpindaResolver
from src.registry.database import SpindaRegistry
from src.data.high_fidelity_generator import generate_high_fidelity_spinda
from src.utils.detector import SpindaDetector # Import the detector

def identify_spinda(image_path: str):
    if not os.path.exists(image_path):
        print(f"Error: File {image_path} not found.")
        return

    print(f"--- Identifying Spinda in {image_path} ---")
    
    # 1. Detect and Crop Spinda
    detector = SpindaDetector()
    cropped_img = detector.detect_and_crop(image_path)

    if cropped_img is None:
        print("Error: Could not detect Spinda in the image.")
        return
    
    # Save cropped image for debug/visual check
    cv2.imwrite("detected_spinda_crop.png", cropped_img)
    print("Detected Spinda saved to detected_spinda_crop.png")

    # We need to save the cropped image to a temporary file for the inference model to read
    temp_cropped_path = "temp_cropped_spinda.png"
    cv2.imwrite(temp_cropped_path, cropped_img)

    # 2. Inference (Model Prediction) using the cropped image
    try:
        inf = SpindaInference(model_path="models/best_spinda_model.pth")
        coords, fingerprint = inf.predict(temp_cropped_path)
    except Exception as e:
        print(f"Error during inference: {e}")
        os.remove(temp_cropped_path) # Clean up temp file
        return
    finally:
        os.remove(temp_cropped_path) # Clean up temp file

    print(f"Visual Fingerprint: {fingerprint}")
    print(f"Predicted Grid Coordinates: {coords}")

    # 3. Resolution (Mathematical PIDs)
    resolved = SpindaResolver.resolve_fingerprint(fingerprint)
    print("\nPossible PIDs:")
    print(f"  Standard (Gen 3-8, HOME): 0x{resolved['standard']}")
    print(f"  BDSP (Big-Endian Flip):   0x{resolved['bdsp']}")

    # 4. Visual Verification
    print("\nGenerating visual verification image...")
    verify_img = generate_high_fidelity_spinda(int(resolved['standard'], 16))
    cv2.imwrite("prediction_verify.png", verify_img)
    print("Verification image saved to: prediction_verify.png")

    # 5. Registry Lookup
    reg = SpindaRegistry()
    matches = reg.lookup_by_fingerprint(fingerprint)
    
    if matches:
        print("\nMatches found in Global Registry:")
        for pid in matches:
            print(f"  - Registered PID: 0x{pid}")
    else:
        print("\nNo matching entries in Global Registry.")

    print("\nNote: Accuracy depends on model training progress.")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python identify.py <image_path>")
    else:
        identify_spinda(sys.argv[1])
