
import argparse 
import json 
import sys 

from .detector import OllamaLogoDetector 
from .camera import capture_and_analyze ,start_interactive_capture 

def main ():
    parser =argparse .ArgumentParser (
    description ="Detect logos and companies using Ollama vision models"
    )

    parser .add_argument ("--image","-i",type =str )
    parser .add_argument ("--model","-m",type =str ,default ="ministral-3:latest")
    parser .add_argument ("--output","-o",type =str )
    parser .add_argument ("--host",type =str )
    parser .add_argument ("--single","-s",action ="store_true")
    parser .add_argument ("--no-save",action ="store_true")
    parser .add_argument ("--output-dir",type =str ,default ="./captures")

    args =parser .parse_args ()

    try :
        if args .image :
            print (f"Analyzing: {args .image }")
            print (f"Model: {args .model }")

            detector =OllamaLogoDetector (model =args .model ,host =args .host )
            result =detector .detect_from_file (args .image )

            _print_results (result )

            if args .output :
                with open (args .output ,'w')as f :
                    json .dump (result ,f ,indent =2 )
                print (f"Results saved to: {args .output }")

        elif args .single :
            result =capture_and_analyze (
            model =args .model ,
            save_image =not args .no_save ,
            output_dir =args .output_dir 
            )

            if args .output and result :
                with open (args .output ,'w')as f :
                    json .dump (result ,f ,indent =2 )
                print (f"Results saved to: {args .output }")

        else :
            start_interactive_capture (
            model =args .model ,
            save_images =not args .no_save ,
            output_dir =args .output_dir 
            )

    except KeyboardInterrupt :
        sys .exit (0 )
    except Exception as e :
        print (f"Error: {e }")
        sys .exit (1 )

def _print_results (result :dict ):
    print ("\n"+"="*50 )
    print ("DETECTION RESULTS")
    print ("="*50 )

    logos =result .get ("logos_detected",[])
    count =result .get ("total_count",len (logos ))

    if count ==0 :
        print ("\nNo logos or companies detected")
        if desc :=result .get ("description"):
            print (f"\nImage description: {desc }")
    else :
        print (f"\nFound {count } logo(s)/company(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","N/A")

            print (f"  {i }. {brand }")
            print (f"     Confidence: {conf }")
            print (f"     Location:   {loc }")
            print (f"     Category:   {cat }")
            print ()

    if "error"in result :
        print (f"\nError occurred: {result ['error']}")

    if "raw_response"in result and result .get ("parse_error"):
        print (f"\nParse error: {result ['parse_error']}")
        print (f"Raw response:\n{result ['raw_response'][:500 ]}...")

    print ("="*50 )
    print ("\nRaw JSON:")
    print (json .dumps (result ,indent =2 ))

if __name__ =="__main__":
    main ()
