import cv2
import json
import numpy as np
from datetime import datetime
from pathlib import Path
from typing import Dict, Optional
from ..ollama.detector import OllamaLogoDetector

def capture_and_analyze(model: str = "ministral-3:latest",
                        save_image: bool = True,
                        output_dir: Optional[str] = None) -> Dict:
    cap = cv2.VideoCapture(0)
    if not cap.isOpened():
        raise RuntimeError("Could not access camera")
    
    print("Camera ready. Press SPACE to capture, Q to quit.")
    
    result = None
    
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        
        display = frame.copy()
        cv2.putText(display, "Press SPACE to capture | Q to quit", 
                   (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
        cv2.imshow("Capture", display)
        
        key = cv2.waitKey(1) & 0xFF
        
        if key == ord(' '):
            print("Analyzing image...")
            
            if save_image:
                if output_dir is None:
                    output_dir = "./captures"
                Path(output_dir).mkdir(parents=True, exist_ok=True)
                
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                img_path = Path(output_dir) / f"capture_{timestamp}.jpg"
                cv2.imwrite(str(img_path), frame)
                print(f"Saved: {img_path}")
            
            detector = OllamaLogoDetector(model=model)
            result = detector.detect_from_numpy(frame)
            
            _display_results(result)
            break
            
        elif key == ord('q'):
            break
    
    cap.release()
    cv2.destroyAllWindows()
    
    return result if result else {"logos_detected": [], "total_count": 0}

def start_interactive_capture(model: str = "ministral-3:latest",
                               save_images: bool = True,
                               output_dir: Optional[str] = None):
    cap = cv2.VideoCapture(0)
    if not cap.isOpened():
        raise RuntimeError("Could not access camera")
    
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    
    print("=" * 60)
    print("Ollama Logo Detection - Interactive Mode")
    print("=" * 60)
    print(f"Camera: {width}x{height}")
    print(f"Model: {model}")
    print("\nControls:")
    print("  SPACE - Capture and analyze")
    print("  S     - Save frame only")
    print("  R     - Show last results")
    print("  Q     - Quit")
    print("=" * 60)
    
    detector = OllamaLogoDetector(model=model)
    last_result = None
    analyzing = False
    status_message = "Ready - Press SPACE to capture"
    
    if output_dir is None:
        output_dir = "./captures"
    Path(output_dir).mkdir(parents=True, exist_ok=True)
    
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        
        display = frame.copy()
        
        cv2.rectangle(display, (0, 0), (width, 40), (40, 40, 40), -1)
        cv2.putText(display, status_message, (10, 28),
                   cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
        
        if last_result and last_result.get("logos_detected"):
            brands = [l.get("brand", "?") for l in last_result["logos_detected"]]
            brand_text = f"Detected: {', '.join(brands[:3])}"
            if len(brands) > 3:
                brand_text += f" +{len(brands)-3} more"
            cv2.rectangle(display, (0, height-35), (width, height), (40, 40, 40), -1)
            cv2.putText(display, brand_text, (10, height-10),
                       cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 2)
        
        cv2.imshow("Ollama Logo Detection", display)
        
        key = cv2.waitKey(1) & 0xFF
        
        if key == ord(' ') and not analyzing:
            analyzing = True
            status_message = "Analyzing with Ollama..."
            cv2.imshow("Ollama Logo Detection", display)
            cv2.waitKey(1)
            
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            img_path = Path(output_dir) / f"capture_{timestamp}.jpg"
            
            if save_images:
                cv2.imwrite(str(img_path), frame)
            
            last_result = detector.detect_from_numpy(frame)
            
            json_path = Path(output_dir) / f"result_{timestamp}.json"
            with open(json_path, 'w') as f:
                json.dump(last_result, f, indent=2)
            
            count = last_result.get("total_count", 0)
            if count > 0:
                status_message = f"Found {count} logo(s)! Press R for details"
            else:
                status_message = "No logos detected. Try again!"
            
            print(f"\nCaptured: {img_path}")
            print(f"Results: {json_path}")
            _display_results(last_result)
            
            analyzing = False
            
        elif key == ord('s'):
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            img_path = Path(output_dir) / f"capture_{timestamp}.jpg"
            cv2.imwrite(str(img_path), frame)
            status_message = f"Saved: {img_path.name}"
            print(f"Saved: {img_path}")
            
        elif key == ord('r') and last_result:
            print("\n" + "=" * 40)
            print("Last Detection Results:")
            print("=" * 40)
            _display_results(last_result)
            
        elif key == ord('q'):
            break
    
    cap.release()
    cv2.destroyAllWindows()
    
    print("\nGoodbye!")
    return last_result

def _display_results(result: Dict):
    print("\n" + "-" * 40)
    
    logos = result.get("logos_detected", [])
    count = result.get("total_count", len(logos))
    
    if count == 0:
        print("No logos or brands detected")
        if "description" in result:
            print(f"Description: {result['description']}")
    else:
        print(f"Detected {count} logo(s)/brand(s):\n")
        for i, logo in enumerate(logos, 1):
            brand = logo.get("brand", "Unknown")
            conf = logo.get("confidence", "unknown")
            loc = logo.get("location", "unknown")
            cat = logo.get("category", "")
            
            print(f"  {i}. {brand}")
            print(f"     Confidence: {conf}")
            print(f"     Location: {loc}")
            if cat:
                print(f"     Category: {cat}")
            print()
    
    if "error" in result:
        print(f"Error: {result['error']}")
    
    print("-" * 40)
    
    print("\nJSON Output:")
    print(json.dumps(result, indent=2))
