"""Ingest lab inbox images (receipts/photos) using AI vision to extract inventory items."""

import base64
import csv
import json
import os
import shutil
import uuid
from datetime import date
from pathlib import Path
from typing import Any, Dict, List


def _encode_image(image_path: str) -> str:
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")


def _analyze_image(client, image_path: str) -> List[Dict[str, Any]]:
    base64_image = _encode_image(image_path)

    prompt = """
    Analyze this image for a Luthier's Laboratory Inventory.

    1. If it is a **Receipt**, extract the items purchased. Ignore taxes/fees.
    2. If it is a **Photo of an object**, identify what it is. ESTIMATE the quantity visible.

    Return a STRICT JSON array of objects. Do not include markdown formatting.
    Schema:
    [
        {
            "name": "Item Name",
            "category": "Consumables" | "Wood" | "Parts" | "Tools" | "Other",
            "quantity": "1",
            "vendor": "Vendor Name (or 'Unknown')",
            "notes": "Any details (size, color, specs)"
        }
    ]
    """

    try:
        response = client.chat.completions.create(
            model=os.environ.get("OPENAI_MODEL", "gpt-4o"),
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": prompt},
                        {
                            "type": "image_url",
                            "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},
                        },
                    ],
                }
            ],
            max_tokens=1000,
        )
        content = response.choices[0].message.content
        content = content.replace("```json", "").replace("```", "").strip()
        return json.loads(content)

    except Exception:
        return []


def _append_to_csv(output_csv: str, items: List[Dict[str, Any]]) -> None:
    file_exists = os.path.exists(output_csv)
    Path(output_csv).parent.mkdir(parents=True, exist_ok=True)

    with open(output_csv, "a", newline="", encoding="utf-8") as f:
        fieldnames = [
            "id", "name", "seller", "species", "price", "listed_date",
            "status", "image_url", "link", "dimensions", "figure",
            "category", "raw_attributes",
        ]
        writer = csv.DictWriter(f, fieldnames=fieldnames)

        if not file_exists:
            writer.writeheader()

        for item in items:
            row = {
                "id": f"lab_{uuid.uuid4().hex[:8]}",
                "name": item.get("name", "Unknown Item"),
                "seller": "Shelley Lab (Stock)",
                "species": item.get("category", "Other"),
                "price": "Owned",
                "listed_date": date.today().isoformat(),
                "status": "In Stock",
                "image_url": "",
                "link": "",
                "dimensions": item.get("notes", ""),
                "figure": "",
                "category": item.get("category", "Other"),
                "raw_attributes": f"Qty: {item.get('quantity', '1')}, Vendor: {item.get('vendor', 'Unknown')}",
            }
            writer.writerow(row)


def run(data_dir: str) -> str:
    """Process images in data_dir/lab_inbox/ using OpenAI vision, output to data_dir/raw/shelley_lab.csv."""
    from mentorr.helpers import get_openai_client

    client = get_openai_client()
    if client is None:
        return "OpenAI API key not configured. Set OPENAI_API_KEY to enable lab inbox processing."

    data_path = Path(data_dir)
    inbox_dir = data_path / "lab_inbox"
    processed_dir = data_path / "lab_processed"
    output_csv = str(data_path / "raw" / "shelley_lab.csv")

    if not inbox_dir.exists():
        return "Lab inbox directory not found."

    files = [f for f in inbox_dir.iterdir() if f.suffix.lower() in (".png", ".jpg", ".jpeg", ".webp")]

    if not files:
        return "No images in lab inbox."

    messages = [f"Found {len(files)} images to process."]
    processed_dir.mkdir(parents=True, exist_ok=True)

    for filepath in files:
        items = _analyze_image(client, str(filepath))
        if items:
            _append_to_csv(output_csv, items)
            shutil.move(str(filepath), str(processed_dir / filepath.name))
            messages.append(f"  Processed {filepath.name}: {len(items)} items extracted")
        else:
            messages.append(f"  Failed to extract items from {filepath.name}")

    return "\n".join(messages)


if __name__ == "__main__":
    import sys
    data_dir = sys.argv[1] if len(sys.argv) > 1 else "."
    print(run(data_dir))
