"""Storage operations for WebView CLI - Using execute_script for sync operations."""

from __future__ import annotations

from typing import Any, Dict, List, Optional


class StorageOps:
    """Storage operations using synchronous execute_script."""

    def __init__(self, controller: Any):
        self.controller = controller

    def get_cookies(self, domain: Optional[str] = None) -> List[Dict[str, Any]]:
        """Get cookies using context API."""
        try:
            context = self.controller._adapter._context
            if hasattr(context, 'cookies'):
                cookies = context.cookies
                if isinstance(cookies, list):
                    if domain:
                        return [c for c in cookies if domain in c.get("domain", "")]
                    return cookies
        except Exception:
            pass
        return []

    def set_cookie(self, name: str, value: str, **kwargs) -> None:
        """Set a cookie using execute_script."""
        self.controller.execute_script(
            f"document.cookie = '{name}={value}; path=/'"
        )

    def delete_cookie(self, name: str) -> None:
        """Delete a cookie using execute_script."""
        self.controller.execute_script(
            f"document.cookie = '{name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/'"
        )

    def clear_cookies(self) -> None:
        """Clear all cookies."""
        try:
            context = self.controller._adapter._context
            if hasattr(context, 'clear_cookies'):
                context.clear_cookies()
        except Exception:
            pass

    def get_local_storage(self) -> Dict[str, str]:
        """Get all localStorage items."""
        result = self.controller.execute_script("""
            () => {
                const items = {};
                try {
                    for (let i = 0; i < localStorage.length; i++) {
                        const key = localStorage.key(i);
                        items[key] = localStorage.getItem(key);
                    }
                } catch (e) {
                    console.error('localStorage error:', e);
                }
                return items;
            }
        """)
        return result or {}

    def get_local_storage_item(self, key: str) -> Optional[str]:
        """Get a localStorage item."""
        return self.controller.execute_script(
            "(key) => { try { return localStorage.getItem(key); } catch (e) { return null; } }",
            key
        )

    def set_local_storage_item(self, key: str, value: str) -> None:
        """Set a localStorage item."""
        self.controller.execute_script(
            "(key, value) => { try { localStorage.setItem(key, value); } catch (e) { console.error(e); } }",
            key,
            value
        )

    def delete_local_storage_item(self, key: str) -> None:
        """Delete a localStorage item."""
        self.controller.execute_script(
            "(key) => { try { localStorage.removeItem(key); } catch (e) { console.error(e); } }",
            key
        )

    def clear_local_storage(self) -> None:
        """Clear all localStorage."""
        self.controller.execute_script(
            "() => { try { localStorage.clear(); } catch (e) { console.error(e); } }"
        )

    def get_session_storage(self) -> Dict[str, str]:
        """Get all sessionStorage items."""
        result = self.controller.execute_script("""
            () => {
                const items = {};
                try {
                    for (let i = 0; i < sessionStorage.length; i++) {
                        const key = sessionStorage.key(i);
                        items[key] = sessionStorage.getItem(key);
                    }
                } catch (e) {
                    console.error('sessionStorage error:', e);
                }
                return items;
            }
        """)
        return result or {}

    def set_session_storage_item(self, key: str, value: str) -> None:
        """Set a sessionStorage item."""
        self.controller.execute_script(
            "(key, value) => { try { sessionStorage.setItem(key, value); } catch (e) { console.error(e); } }",
            key,
            value
        )

    def delete_session_storage_item(self, key: str) -> None:
        """Delete a sessionStorage item."""
        self.controller.execute_script(
            "(key) => { try { sessionStorage.removeItem(key); } catch (e) { console.error(e); } }",
            key
        )

    def clear_session_storage(self) -> None:
        """Clear all sessionStorage."""
        self.controller.execute_script(
            "() => { try { sessionStorage.clear(); } catch (e) { console.error(e); } }"
        )
