from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Any

from playwright.sync_api import sync_playwright


@dataclass
class SpiderAgent:
    model_provider: str = "openai"
    model_name: str = "gpt-4o"
    api_key: str | None = None
    headless: bool = True
    viewport_width: int = 1440
    viewport_height: int = 900

    def run(
        self,
        task: str,
        start_url: str,
        output_schema: dict[str, Any] | None = None,
        screenshot_path: str = "artifacts/last.png",
    ) -> dict[str, Any]:
        output_file = Path(screenshot_path)
        output_file.parent.mkdir(parents=True, exist_ok=True)

        with sync_playwright() as playwright:
            browser = playwright.chromium.launch(headless=self.headless)
            context = browser.new_context(
                viewport={"width": self.viewport_width, "height": self.viewport_height}
            )
            page = context.new_page()
            page.goto(start_url, wait_until="domcontentloaded")
            page.screenshot(path=str(output_file), full_page=True)
            title = page.title()
            current_url = page.url
            browser.close()

        return {
            "status": "ok",
            "task": task,
            "model": {
                "provider": self.model_provider,
                "name": self.model_name,
            },
            "start_url": start_url,
            "current_url": current_url,
            "page_title": title,
            "screenshot": str(output_file),
            "output_schema": output_schema,
            "note": "MVP skeleton: capture + observe only, decision loop will come in next versions.",
        }
