"""Teste US-011 (PRD 5.8) — avertisment overlap NEBLOCANT la salvarea regulii text.

Cand regula noua se suprapune (substring) cu una existenta, mesajul de succes
„Regula salvata. Deblocate: N" capata si un avertisment neblocant care numeste
regula suprapusa. Salvarea CONTINUA (regula se salveaza oricum).
"""

from __future__ import annotations

import os
import re
import tempfile

import pytest
from starlette.testclient import TestClient


def _create_account_user(email: str, name: str = "Service", password: str = "parolasecreta10"):
    from app.accounts import create_account
    from app.users import create_user
    from app.db import get_connection

    conn = get_connection()
    try:
        acct_id = create_account(conn, name, active=True)
        create_user(conn, acct_id, email, password)
        return acct_id
    finally:
        conn.close()


def _login(client, email: str, password: str = "parolasecreta10") -> None:
    resp = client.get("/login")
    m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text)
    assert m
    resp = client.post("/login", data={"email": email, "parola": password, "csrf_token": m.group(1)})
    assert resp.status_code == 303


def _csrf(client) -> str:
    resp = client.get("/?tab=mapari")
    m = re.search(r'name="csrf_token"\s+value="([^"]+)"', resp.text)
    assert m, "csrf_token negasit"
    return m.group(1)


def _seed_text_rule(acct: int, pattern: str, cod: str, auto_send: int = 0) -> None:
    from app.db import get_connection
    conn = get_connection()
    try:
        conn.execute(
            "INSERT INTO operation_text_rules (account_id, pattern, cod_prestatie, auto_send) "
            "VALUES (?, ?, ?, ?)",
            (acct, pattern, cod, auto_send),
        )
        conn.commit()
    finally:
        conn.close()


def _text_rules(acct: int) -> list[dict]:
    from app.db import get_connection
    from app.mapping import load_text_rules
    conn = get_connection()
    try:
        return load_text_rules(conn, acct)
    finally:
        conn.close()


@pytest.fixture()
def client(monkeypatch):
    tmp = tempfile.mkdtemp()
    monkeypatch.setenv("AUTOPASS_DB_PATH", os.path.join(tmp, "overlap.db"))
    monkeypatch.setenv("AUTOPASS_WEB_AUTH_REQUIRED", "true")
    from app.config import get_settings
    get_settings.cache_clear()
    from app.web import ratelimit
    ratelimit._hits.clear()
    from app.main import app
    with TestClient(app, follow_redirects=False) as c:
        yield c
    ratelimit._hits.clear()
    get_settings.cache_clear()


def test_salvare_cu_overlap_arata_avertisment_dar_salveaza(client):
    """Regula noua care se suprapune cu una existenta -> avertisment + salvare.

    Exista „verificare" -> OE-2; salvam „verificare faruri" -> OE-3. „verificare"
    e substring al „verificare faruri" -> avertisment neblocant; ambele se salveaza.
    """
    acct = _create_account_user("ov@test.com")
    _seed_text_rule(acct, "verificare", "OE-2")

    _login(client, "ov@test.com")
    csrf = _csrf(client)
    resp = client.post("/mapari/reguli-text", data={
        "pattern": "verificare faruri", "cod_prestatie": "OE-3", "csrf_token": csrf,
    })
    assert resp.status_code == 200
    # mesaj de succes pastrat
    assert "Regula salvata" in resp.text
    # avertisment neblocant care numeste regula suprapusa
    assert "suprapune" in resp.text.lower()
    assert "verificare" in resp.text

    # ambele reguli persistate
    patterns = {r["pattern"] for r in _text_rules(acct)}
    assert patterns == {"verificare", "verificare faruri"}
