#!/usr/bin/env python3
"""
verify_qr_setup.py
Quick verification script to check QR code and JSON file setup
"""

import os
import json
from pathlib import Path

def print_section(title):
    print("\n" + "="*70)
    print(f"  {title}")
    print("="*70)

def check_directories():
    """Check if required directories exist"""
    print_section("?? Directory Structure Check")
    
    dirs = [
        "static/json/vannamei",
        "static/json/monodon",
        "static/json/indicus",
        "static/qrcodes/vannamei",
        "static/qrcodes/monodon",
        "static/qrcodes/indicus",
    ]
    
    for dir_path in dirs:
        exists = os.path.exists(dir_path)
        status = "?" if exists else "?"
        print(f"{status} {dir_path}")
        if exists:
            files = os.listdir(dir_path)
            print(f"   ? {len(files)} files")

def check_json_qr_pairs():
    """Check JSON and QR code pairs"""
    print_section("?? JSON ? QR Code Pairs")
    
    for species in ["vannamei", "monodon", "indicus"]:
        json_dir = f"static/json/{species}"
        qr_dir = f"static/qrcodes/{species}"
        
        if not os.path.exists(json_dir):
            continue
            
        print(f"\n?? {species.upper()}")
        json_files = [f for f in os.listdir(json_dir) if f.endswith('.json')]
        
        for json_file in json_files[:5]:  # Show first 5
            json_path = os.path.join(json_dir, json_file)
            qr_file = json_file.replace('.json', '.png')
            qr_path = os.path.join(qr_dir, qr_file)
            
            json_exists = os.path.exists(json_path)
            qr_exists = os.path.exists(qr_path)
            
            status = "?" if (json_exists and qr_exists) else "??"
            print(f"  {status} {json_file}")
            print(f"      JSON: {'?' if json_exists else '?'} | QR: {'?' if qr_exists else '?'}")
            
            if json_exists:
                try:
                    with open(json_path, 'r') as f:
                        data = json.load(f)
                    # Try to extract batch ID
                    batch_id = (
                        data.get('parent_batch_id') or 
                        data.get('Unique ID') or 
                        data.get('ID') or
                        'N/A'
                    )
                    print(f"      Batch ID: {batch_id}")
                except:
                    print(f"      ?? Could not read JSON")
        
        if len(json_files) > 5:
            print(f"  ... and {len(json_files) - 5} more files")

def check_sample_urls():
    """Generate sample URLs for testing"""
    print_section("?? Sample Test URLs")
    
    from config import PUBLIC_BASE_URL
    base_url = PUBLIC_BASE_URL
    
    for species in ["vannamei", "monodon", "indicus"]:
        json_dir = f"static/json/{species}"
        if not os.path.exists(json_dir):
            continue
            
        json_files = [f for f in os.listdir(json_dir) if f.endswith('.json')]
        if json_files:
            sample_file = json_files[0]
            print(f"\n{species.upper()}:")
            print(f"  Block JSON Viewer:")
            print(f"  {base_url}/block_json/{species}/{sample_file}")
            print(f"\n  Direct JSON:")
            print(f"  {base_url}/static/json/{species}/{sample_file}")
            print(f"\n  QR Image:")
            qr_file = sample_file.replace('.json', '.png')
            print(f"  {base_url}/static/qrcodes/{species}/{qr_file}")

def check_export_index():
    """Check export index file"""
    print_section("?? Export Index")
    
    index_path = "static/json/export_index.json"
    if os.path.exists(index_path):
        print("? Export index found")
        try:
            with open(index_path, 'r') as f:
                index = json.load(f)
            for species, info in index.items():
                print(f"\n{species.upper()}:")
                print(f"  Blocks: {info.get('count', 0)}")
                print(f"  Files: {len(info.get('files', []))}")
                print(f"  QR Codes: {len(info.get('qr_codes', []))}")
        except Exception as e:
            print(f"?? Could not read index: {e}")
    else:
        print("? Export index not found")
        print("   Run: python export_blocks_to_json_and_qr.py")

def check_template_files():
    """Check if required templates exist"""
    print_section("?? Template Files")
    
    templates = [
        "templates/lineage_block_view.html",
        "templates/block_json_view.html",
    ]
    
    for template in templates:
        exists = os.path.exists(template)
        status = "?" if exists else "?"
        print(f"{status} {template}")

def main():
    print_section("?? Blockchain QR Setup Verification")
    print("Checking your setup for individual block QR codes...")
    
    check_directories()
    check_export_index()
    check_json_qr_pairs()
    check_template_files()
    check_sample_urls()
    
    print_section("? Verification Complete")
    print("\n?? Next Steps:")
    print("1. If files are missing, run: python export_blocks_to_json_and_qr.py")
    print("2. Start Flask: python app.py")
    print("3. Test URLs shown above in your browser")
    print("4. Visit: https://ciba.res.in/laksyashrimp/lineage_block/vannamei/1")
    print()

if __name__ == "__main__":
    main()