#!/usr/bin/env python
"""Analyze a screenshot image file via Gemini to answer structured questions.

Uses GEMINI_API_KEY from environment.
Returns JSON with these answers:
- has_page_content: bool - does the page show meaningful text/content?
- has_images: bool - are visible images/thumbnails present on the page?
- cookie_consent_shown: bool - is a cookie consent banner/overlay visible?
- page_title_text: str - any visible title/heading text
- accept_button_visible: bool - is an accept/agree button visible?
- accept_button_text: str | null - text on the accept button
- summary: str - one-sentence description of what's on the page
"""

from __future__ import annotations

import json
import os
import sys
import time
from pathlib import Path

from google import genai
from google.genai import types

MODEL = "models/gemini-3.1-flash-lite-preview"

SCHEMA: dict = {
    "type": "object",
    "additionalProperties": False,
    "required": [
        "has_page_content",
        "has_images",
        "cookie_consent_shown",
        "page_title_text",
        "accept_button_visible",
        "accept_button_text",
        "summary",
    ],
    "properties": {
        "has_page_content": {"type": "boolean"},
        "has_images": {"type": "boolean"},
        "cookie_consent_shown": {"type": "boolean"},
        "page_title_text": {"type": "string"},
        "accept_button_visible": {"type": "boolean"},
        "accept_button_text": {"type": ["string", "null"]},
        "summary": {"type": "string"},
    },
}


def analyze_image(image_path: str | Path) -> dict:
    image_path = Path(image_path)
    if not image_path.exists():
        return {"error": f"File not found: {image_path}", "path": str(image_path)}

    api_key = os.environ.get("GEMINI_API_KEY", "")
    if not api_key:
        return {"error": "GEMINI_API_KEY not set in environment", "path": str(image_path)}

    client = genai.Client(api_key=api_key)

    try:
        image_bytes = image_path.read_bytes()
    except Exception as exc:
        return {"error": f"Cannot read image: {exc}", "path": str(image_path)}

    prompt = """Analyze this screenshot of a webpage. Answer these questions:

1. Does the page show any content (text, paragraphs, headings, product listings)? Not just a blank/white/loading page.
2. Are there visible images, thumbnails, or photo elements on the page?
3. Is there a cookie consent banner, GDPR overlay, or privacy consent dialog visible?
4. What is the main title or heading text visible on the page?
5. If a cookie consent is shown, is there a visible accept/agree/all button?
6. What text is on that accept button (if visible)?
7. Write a one-sentence summary describing what you see.

IMPORTANT: If the page is blank, white, or showing only a loading state, set has_page_content=false."""

    started = time.perf_counter()
    try:
        response = client.models.generate_content(
            model=MODEL,
            contents=[
                types.Part.from_bytes(data=image_bytes, mime_type="image/png"),
                prompt,
            ],
            config=types.GenerateContentConfig(
                response_mime_type="application/json",
                response_schema=SCHEMA,
                temperature=0.0,
            ),
        )
        elapsed = time.perf_counter() - started
        result = json.loads(response.text)
        result["_elapsed_s"] = round(elapsed, 2)
        result["_model"] = MODEL
        result["_path"] = str(image_path)
        return result
    except Exception as exc:
        return {"error": f"Gemini API error: {exc}", "path": str(image_path), "_elapsed_s": round(time.perf_counter() - started, 2)}


def main() -> None:
    import argparse
    p = argparse.ArgumentParser(description="Analyze a screenshot via Gemini")
    p.add_argument("image", help="Path to screenshot PNG")
    p.add_argument("--json", action="store_true", help="Output raw JSON only")
    args = p.parse_args()

    result = analyze_image(args.image)

    if args.json:
        print(json.dumps(result, ensure_ascii=False, indent=2))
        return

    if "error" in result:
        print(f"ERROR: {result['error']}")
        sys.exit(1)

    print(f"Page content:   {'YES' if result.get('has_page_content') else 'NO'}")
    print(f"Images visible: {'YES' if result.get('has_images') else 'NO'}")
    print(f"Cookie consent: {'YES' if result.get('cookie_consent_shown') else 'NO'}")
    print(f"Title:          {result.get('page_title_text') or '(none)'}")
    print(f"Accept button:  {'YES' if result.get('accept_button_visible') else 'NO'}")
    print(f"Button text:    {result.get('accept_button_text') or '(none)'}")
    print(f"Summary:        {result.get('summary')}")
    print(f"Elapsed:        {result.get('_elapsed_s')}s")


if __name__ == "__main__":
    main()
