import os
import re
from pathlib import Path

import pytest
import requests
from dotenv import dotenv_values

frontend_env = dotenv_values("/app/frontend/.env")
base_url = os.environ.get("REACT_APP_BACKEND_URL") or frontend_env.get("REACT_APP_BACKEND_URL")
if not base_url:
    raise RuntimeError("REACT_APP_BACKEND_URL missing")
BASE_URL = base_url.rstrip("/")
API = f"{BASE_URL}/api"

# Local dovecot test IMAP server (backend-local)
IMAP = {
    "src": {"host": "127.0.0.1", "port": 143, "email": "user1", "password": "pass1", "ssl": False},
    "dst": {"host": "127.0.0.1", "port": 143, "email": "user2", "password": "pass2", "ssl": False},
}


@pytest.fixture(scope="session")
def test_credentials():
    p = Path("/app/memory/test_credentials.md")
    if not p.exists():
        pytest.skip("missing test_credentials.md")
    c = p.read_text(encoding="utf-8")
    e = re.search(r'(?im)^\s*(?:[-*]\s*)?(?:\*\*)?email(?:\*\*)?\s*:\s*`?([^`\s]+)', c)
    pw = re.search(r'(?im)^\s*(?:[-*]\s*)?(?:\*\*)?password(?:\*\*)?\s*:\s*`?([^`\s]+)', c)
    if not e or not pw:
        pytest.skip("no creds in test_credentials.md")
    return {"email": e.group(1), "password": pw.group(1)}


@pytest.fixture(scope="session")
def api_client():
    s = requests.Session()
    s.headers.update({"Content-Type": "application/json"})
    return s


@pytest.fixture(scope="session")
def auth_token(test_credentials):
    r = requests.post(f"{API}/auth/login", json=test_credentials, timeout=30)
    if r.status_code != 200:
        pytest.fail(f"login failed {r.status_code}: {r.text[:300]}")
    t = r.json().get("token")
    if not t:
        pytest.fail("no token in login response")
    return t


@pytest.fixture(scope="session")
def client(auth_token):
    s = requests.Session()
    s.headers.update({"Content-Type": "application/json",
                      "Authorization": f"Bearer {auth_token}"})
    return s


def mig_payload(name):
    return {
        "name": name,
        "source_host": IMAP["src"]["host"], "source_port": IMAP["src"]["port"],
        "source_email": IMAP["src"]["email"], "source_password": IMAP["src"]["password"],
        "source_ssl": False,
        "dest_host": IMAP["dst"]["host"], "dest_port": IMAP["dst"]["port"],
        "dest_email": IMAP["dst"]["email"], "dest_password": IMAP["dst"]["password"],
        "dest_ssl": False,
    }


@pytest.fixture(scope="module")
def created_ids():
    return []


@pytest.fixture(scope="module", autouse=True)
def cleanup(client, created_ids):
    yield
    for mid in created_ids:
        try:
            client.delete(f"{API}/migrations/{mid}", timeout=30)
        except Exception:
            pass
