"""Safety policy enforced in code, outside the model. The model can be tricked; this cannot."""

from __future__ import annotations

import re
from dataclasses import dataclass, field
from typing import Iterable, Optional, Set
from urllib.parse import urlparse

from .actions import Action
from .dom import Observation

RISKY_WORDS = re.compile(
    r"\b(buy|purchase|pay|checkout|place order|subscribe|delete|remove account|transfer|send|"
    r"submit|confirm|publish|post|sign up|accept)\b",
    re.IGNORECASE,
)

INJECTION_PATTERNS = re.compile(
    r"(ignore (all |any )?(previous|prior|above) instructions|disregard (your|the) (instructions|rules)|"
    r"you are now|new instructions:|system prompt|as an ai agent you must|do not tell the user)",
    re.IGNORECASE,
)


def looks_like_injection(text: str) -> bool:
    """Cheap heuristic flag for text that tries to instruct the agent. Not a defense by itself."""
    return bool(INJECTION_PATTERNS.search(text))


@dataclass
class PolicyDecision:
    allowed: bool
    needs_confirmation: bool = False
    reason: str = ""


@dataclass
class Policy:
    allowed_domains: Set[str] = field(default_factory=set)  # empty = any domain
    confirm_risky_clicks: bool = True
    allow_sensitive_typing: bool = False

    def domain_ok(self, url: str) -> bool:
        host = (urlparse(url).hostname or "").lower()
        if urlparse(url).scheme not in ("http", "https"):
            return False
        if not self.allowed_domains:
            return True
        return any(host == d or host.endswith("." + d) for d in self.allowed_domains)

    def check(self, action: Action, obs: Observation) -> PolicyDecision:
        if action.name == "goto":
            if not self.domain_ok(action.args["url"]):
                return PolicyDecision(False, reason=f"domain not allowed: {action.args['url']}")
            return PolicyDecision(True)

        if action.name in ("click", "type", "select"):
            el = obs.by_index(action.args["index"])
            if el is None:
                return PolicyDecision(False, reason=f"no element with index {action.args['index']}")
            if action.name == "type" and el.sensitive and not self.allow_sensitive_typing:
                return PolicyDecision(False, reason="refusing to type into a sensitive field; ask the human")
            if action.name == "click":
                href = el.attrs.get("href", "")
                if href.startswith("http") and not self.domain_ok(href):
                    return PolicyDecision(False, reason=f"link leaves allowed domains: {href}")
                label = " ".join([el.text, el.label, el.attrs.get("value", ""), el.attrs.get("aria-label", "")])
                is_submit = el.attrs.get("type", "").lower() == "submit"
                if self.confirm_risky_clicks and (RISKY_WORDS.search(label) or is_submit):
                    return PolicyDecision(True, needs_confirmation=True,
                                          reason=f"risky click on {el.describe()}")
        return PolicyDecision(True)
