import json
import re
import sqlite3
from datetime import datetime, timedelta
from uuid import uuid4

from flask import render_template
import pytest

from InvestmentManager.leady_pipeline import convert_inbox_to_crm_lead, sync_inbox_from_platform_logs
from InvestmentManager.routes.leady_logs import _stats_from_items
from InvestmentWebsite.offers import lead_spam_guard
from InvestmentWebsite.services import catalog, lead_service, platform_logger
from modules.core import storage_paths


@pytest.fixture()
def form_world(app, monkeypatch, tmp_path):
    from InvestmentWebsite.blueprints.platform import platform
    import flask_mail

    log_db = tmp_path / "platform_logs.db"
    offers = tmp_path / "offers.db"
    with sqlite3.connect(offers) as conn:
        conn.execute("CREATE TABLE EstateData (ID INTEGER PRIMARY KEY, ID_agenta INTEGER, Status_oferty TEXT)")
        conn.executemany("INSERT INTO EstateData VALUES (?, ?, ?)", [(42, 101, "aktywna"), (43, 102, "nieaktywna")])
    monkeypatch.setattr(catalog, "DatabaseConnectionManager", lambda: sqlite3.connect(offers))
    monkeypatch.setattr(storage_paths, "platform_logs_db_path", lambda: log_db)
    monkeypatch.setattr(platform_logger, "_last_cleanup_day", None)
    monkeypatch.setenv("MAIL_USERNAME", "office@example.test")
    monkeypatch.setenv("PLATFORM_EXTRA_RECIPIENT", "extra@example.test")
    monkeypatch.setattr(lead_service, "get_agent_email", lambda agent: f"agent-{agent}@example.test")
    monkeypatch.setattr(flask_mail, "make_msgid", lambda: "<test-message@example.test>")
    sent = []
    monkeypatch.setattr(lead_service.mail, "send", sent.append)
    monkeypatch.setattr(platform, "get_lead_recipients", lambda: ["foreign@example.test"])

    class Later(datetime):
        @classmethod
        def now(cls, tz=None):
            return datetime.now(tz) + timedelta(seconds=30)

    monkeypatch.setattr(lead_spam_guard, "datetime", Later)
    with app.test_request_context():
        token = lead_spam_guard.issue_form_token()
    return log_db, sent, {
        "form_token": token, "website": "", "phone": "500100200",
        "email": "client@example.test", "message": "Proszę o kontakt.",
        "offer_id": "42", "agent_id": "999", "submission_id": str(uuid4()),
    }


def test_domestic_and_foreign_share_inbox_and_conversion(app, form_world):
    log_db, sent, form = form_world
    client = app.test_client()
    assert client.post("/send-lead", data=form).status_code == 200
    assert client.post("/send-lead", data=form).status_code == 200
    assert client.post("/api/platform_send_lead", data={
        **form, "platform": "cyprus", "offer_url": "https://example.test/project",
    }).status_code == 200
    assert len(sent) == 2
    assert set(sent[0].recipients) == {"agent-101@example.test", "office@example.test", "extra@example.test"}
    assert sent[1].recipients == ["foreign@example.test"]

    with sqlite3.connect(log_db) as conn:
        conn.row_factory = sqlite3.Row
        assert sync_inbox_from_platform_logs(conn) == 2
        assert sync_inbox_from_platform_logs(conn) == 0
        rows = conn.execute("SELECT * FROM lead_inbox ORDER BY id").fetchall()
        assert [row["platform"] for row in rows] == ["investment", "cyprus"]
        assert rows[0]["assigned_agent_id"] == 101 and rows[1]["assigned_agent_id"] is None
        assert rows[0]["offer_url"].endswith("/nieruchomosc/42")
        assert rows[0]["message"] == form["message"]
        for row in rows:
            convert_inbox_to_crm_lead(conn, row["id"], created_by=100)
        converted = conn.execute("SELECT * FROM crm_leads ORDER BY id").fetchall()
        assert len(converted) == len(rows)
        for lead, original in zip(converted, rows, strict=True):
            assert lead["source_ref"] == f"lead_inbox:{original['id']}"
            for key in ("platform", "phone", "email", "offer_url"):
                assert lead[key] == original[key]
            assert lead["owner_agent_id"] == original["assigned_agent_id"]
            inbox = conn.execute("SELECT * FROM lead_inbox WHERE id = ?", (original["id"],)).fetchone()
            assert inbox["message"] == form["message"]
            assert inbox["crm_lead_id"] == lead["id"]
            assert inbox["inbox_status"] == "converted"


def test_domestic_storage_failure_does_not_send_and_retry_can_succeed(app, form_world, monkeypatch):
    log_db, sent, form = form_world
    client = app.test_client()
    with monkeypatch.context() as patch:
        def fail():
            raise sqlite3.OperationalError("private database info")

        patch.setattr(platform_logger, "_get_connection", fail)
        result = client.post("/send-lead", data=form)
        assert result.status_code == 500
        assert "private database info" not in result.get_data(as_text=True)
        assert not sent and not log_db.exists()
    assert client.post("/send-lead", data=form).status_code == 200
    assert len(sent) == 1


def test_domestic_smtp_failure_keeps_one_accepted_submission(app, form_world, monkeypatch, caplog):
    log_db, attempts, form = form_world

    def fail(message):
        attempts.append(message)
        raise OSError("private SMTP info")

    monkeypatch.setattr(lead_service.mail, "send", fail)
    client = app.test_client()
    assert client.post("/send-lead", data=form).get_json() == {"success": True}
    assert client.post("/send-lead", data=form).get_json() == {"success": True}
    assert len(attempts) == 1
    assert "private SMTP info" not in caplog.text
    with sqlite3.connect(log_db) as conn:
        row, = conn.execute("SELECT payload FROM platform_logs WHERE log_type='leads'").fetchall()
        assert json.loads(row[0])["status"] == "received"


def test_domestic_target_and_public_guard_fail_closed(app, form_world):
    _, sent, form = form_world
    client = app.test_client()
    assert client.post("/send-lead", data={**form, "offer_id": "43"}).status_code == 404
    assert client.post("/send-lead", data={**form, "website": "filled"}).status_code == 400
    assert client.post("/api/valuation-lead", json={}).status_code == 400
    assert client.post("/api/franczyza/book-meeting", json={}).status_code == 400
    assert not sent


def test_valuation_selects_business_fields_and_does_not_require_consent(app, form_world, monkeypatch):
    _, sent, form = form_world
    records = []
    monkeypatch.setattr(lead_service, "save_valuation_lead", lambda payload: records.append(payload) or 42)
    payload = {
        "form_token": form["form_token"], "website": "", "extra": "private",
        "propertyType": "Dom", "source": "untrusted", "createdAt": "untrusted",
        "location": {"city": "Miasto", "street": "Ulica", "postalCode": "00-001", "region": "mazowieckie", "unknown": "private"},
        "propertyDetails": {"houseArea": 125, "utilities": ["Woda"]},
        "clientGoal": {"primaryGoal": "Sprzedaż", "saleTimeline": "Wkrótce"},
        "contactData": {"fullName": "Jan Testowy", "email": form["email"], "preferredContact": ["Telefon"]},
    }
    client = app.test_client()
    assert client.post("/api/valuation-lead", json=payload).status_code == 400
    assert not records and not sent
    payload["contactData"]["phone"] = form["phone"]
    assert client.post("/api/valuation-lead", json=payload).status_code == 200
    assert len(sent) == len(records) == 1
    stored = records[0]
    assert set(stored) == {"propertyType", "source", "createdAt", "location", "propertyDetails", "clientGoal", "contactData"}
    assert "unknown" not in stored["location"]
    assert "untrusted" not in json.dumps(stored)
    assert stored["propertyDetails"] == payload["propertyDetails"]
    assert stored["contactData"] == payload["contactData"]
    assert sent[0].recipients == lead_service.VALUATION_NOTIFICATION_RECIPIENTS


def test_franchise_rejects_missing_required_name_without_consent_field(app, form_world):
    _, sent, form = form_world
    response = app.test_client().post("/api/franczyza/book-meeting", json={
        "form_token": form["form_token"], "last_name": "Testowy",
        "phone": form["phone"], "start_at": "2030-01-07T09:00",
    })
    assert response.status_code == 400 and not sent


def test_project_urls_are_minimized():
    reduced = platform_logger._minimize_payload({
        "project_url": "https://example.test/item?secret=1#details",
        "all_projects_url": "https://example.test/list?email=value",
    }, "api")
    assert reduced == {"project_url": "https://example.test/item", "all_projects_url": "https://example.test/list"}


@pytest.mark.parametrize("fallback", ["", "Film jest niedostępny.", "<p>Film\njest niedostępny.</p>"])
def test_video_stays_inert_even_with_iframe_fallback(app, fallback):
    with app.test_request_context("/nieruchomosc/42?lang=en"):
        html = render_template(
            "components/offer_description_block.html", description_is_html=True,
            description_text=f'<iframe title="A > B" src="https://www.youtube.com/embed/abcdefghijk">{fallback}</iframe>',
        )
    assert "Load video" in html
    assert "<template><iframe" in html and "</iframe></template>" in html
    assert "sandbox=" in html and "external_video.js" in html


def test_domestic_submissions_do_not_change_foreign_phone_conversion():
    totals = _stats_from_items([
        {"log_type": "leads", "payload": {"platform": "investment"}},
        {"log_type": "leads", "payload": {"platform": "cyprus"}},
        {"log_type": "phone_views", "payload": {"platform": "cyprus"}},
    ])["totals"]
    assert totals["leads_sent"] == 1
    assert totals["conversion_percent"] == 100


@pytest.mark.parametrize("language", ["pl", "en"])
def test_live_form_markup_has_localised_privacy_policy_link(app, language, monkeypatch):
    from InvestmentWebsite.blueprints.investment import investment

    monkeypatch.setattr(investment, "get_agent_card_data", lambda agent_id: None)
    with app.test_request_context(f"/nieruchomosc/42?lang={language}"):
        domestic = render_template("components/agent_card.html", agent_id=101, offer_id=42)

    client = app.test_client()
    forms = [(domestic, "leadForm")]
    for path, form_id in (
        ("/nieruchomosci/cypr", "platform-lead-form"),
        ("/bezplatna-wycena-nieruchomosci", "valuation-form"),
        ("/franczyza/umow-spotkanie", "franchise-booking-form"),
    ):
        response = client.get(f"{path}?lang={language}")
        assert response.status_code == 200
        forms.append((response.get_data(as_text=True), form_id))

    for html, form_id in forms:
        match = re.search(rf"<form\b[^>]*{form_id}[^>]*>(.*?)</form>", html, re.DOTALL)
        assert match, form_id
        form = match[1]
        assert f'lang="{language}"' in form
        assert "href=\"mailto:sebastian.szymoniak@investment-nieruchomosci.com\"" in form
        expected_link = "/privacy-policy" if language == "en" else "/polityka-prywatnosci"
        assert f'href="{expected_link}"' in form
        assert "marketing" not in form.lower()
        assert "franchise-consent" not in form
