import sqlite3

from flask import render_template

from InvestmentWebsite.seo import build_sitemap_urls

from tests.investmentmanager.test_integrator_export_engine_removed import (
    _create_legacy_homepage_databases,
)


def _build_public_app_with_legacy_homepage_db(tmp_path, monkeypatch):
    from modules.core import storage_paths
    from modules.core.app_factory import create_app
    from modules.investment import functions as investment_functions

    monkeypatch.delenv("DATA_DIR", raising=False)
    monkeypatch.setattr(storage_paths, "REPO_ROOT", tmp_path)
    _create_legacy_homepage_databases(tmp_path)

    with sqlite3.connect(tmp_path / "instances" / "IDB.db") as conn:
        conn.executescript(
            """
            ALTER TABLE EstateData ADD COLUMN Data_dodania TEXT;
            ALTER TABLE EstateData ADD COLUMN Typ_nieruchomosci TEXT;
            ALTER TABLE EstateData ADD COLUMN Typ_oferty TEXT;
            ALTER TABLE EstateData ADD COLUMN Liczba_pokoi TEXT;
            ALTER TABLE EstateData ADD COLUMN Miejscowosc TEXT;
            ALTER TABLE EstateData ADD COLUMN ID_agenta INTEGER;
            UPDATE EstateData
            SET Data_dodania = '2026-01-01',
                Typ_nieruchomosci = 'Mieszkanie',
                Typ_oferty = 'Sprzedaz',
                Liczba_pokoi = '2',
                Miejscowosc = 'Testowo',
                ID_agenta = 103;
            """
        )

    with sqlite3.connect(tmp_path / "instances" / "agents.db") as conn:
        conn.executescript(
            """
            ALTER TABLE branches_v2 ADD COLUMN title TEXT;
            ALTER TABLE branches_v2 ADD COLUMN image_url TEXT;
            ALTER TABLE branches_v2 ADD COLUMN info1 TEXT;
            ALTER TABLE branches_v2 ADD COLUMN info2 TEXT;
            UPDATE branches_v2
            SET title = 'Oddzial Test Branch',
                image_url = '',
                info1 = 'Test info',
                info2 = 'Test info 2';

            INSERT INTO agents_v2
                (id, first_name, last_name, email, phone, license, is_active)
            VALUES
                (101, 'Sebastian', 'Szymoniak', 'sebastian@example.test', '500 793 294', 'LIC-101', 1);
            INSERT INTO agent_branches_v2 (agent_id, branch_id)
            VALUES (101, 1);
            INSERT INTO agent_roles_v2 (agent_id, role_id)
            VALUES (101, 1);
            """
        )

    investment_functions.get_estates_count_by_wojewodztwo.cache_clear()
    investment_functions.get_agent_card_data.cache_clear()
    investment_functions.get_branches_office_data.cache_clear()
    investment_functions.get_agents.cache_clear()
    investment_functions.get_branches.cache_clear()
    investment_functions.get_agent_roles.cache_clear()

    app = create_app()
    app.config.update(TESTING=True)
    return app


def test_business_solutions_page_serves(tmp_path, monkeypatch):
    app = _build_public_app_with_legacy_homepage_db(tmp_path, monkeypatch)
    resp = app.test_client().get("/dla-biznesu")

    assert resp.status_code == 200
    html = resp.get_data(as_text=True)
    assert 'href="#kontakt"' in html
    assert 'href="#mozliwosci"' in html
    assert "rodzinnyzakatek.webp" in html


def test_business_solutions_page_renders_agent_101_contact(tmp_path, monkeypatch):
    app = _build_public_app_with_legacy_homepage_db(tmp_path, monkeypatch)
    html = app.test_client().get("/dla-biznesu").get_data(as_text=True)

    assert "Sebastian Szymoniak" in html
    assert 'href="tel:500 793 294"' in html
    assert 'href="mailto:sebastian@example.test"' in html
    assert "Zadzwo" in html
    assert "Napisz e-mail" in html
    assert 'id="leadForm"' not in html
    assert "lead_context" not in html
    assert "investment.send_lead" not in html
    assert "/send-lead" not in html
    assert "shared-lead-submit" not in html
    assert "api/valuation-lead" not in html
    assert "api/franczyza/book-meeting" not in html


def test_agent_card_default_offer_mode_still_renders_offer_lead_form(tmp_path, monkeypatch):
    app = _build_public_app_with_legacy_homepage_db(tmp_path, monkeypatch)
    with app.test_request_context("/"):
        html = render_template(
            "components/agent_card.html",
            agent_id=101,
            name="Sebastian",
            surname="Szymoniak",
            roles="",
            branch="",
            license="LIC-101",
            phone="500 793 294",
            email="sebastian@example.test",
            offer_id=123,
        )

    assert 'id="leadForm"' in html
    assert 'action="/send-lead"' in html
    assert 'name="offer_id" value="123"' in html
    assert "shared-lead-submit" in html
    assert "zapytanie" in html
    assert "123" in html
    assert "lead_context" not in html


def test_send_lead_without_offer_id_keeps_original_validation(tmp_path, monkeypatch):
    app = _build_public_app_with_legacy_homepage_db(tmp_path, monkeypatch)
    resp = app.test_client().post(
        "/send-lead",
        data={
            "phone": "500 793 294",
            "email": "",
            "message": "Prosze o kontakt.",
            "agent_id": "101",
        },
    )

    assert resp.status_code == 400
    assert resp.get_json() == {"success": False, "error": "Brak ID oferty"}


def test_business_solutions_refinement_content(tmp_path, monkeypatch):
    app = _build_public_app_with_legacy_homepage_db(tmp_path, monkeypatch)
    html = app.test_client().get("/dla-biznesu").get_data(as_text=True)

    for label in ["PROJEKT", "PREZENTACJA", "TECHNOLOGIA", "INTEGRACJE", "DYSTRYBUCJA", "LEADY"]:
        assert label in html
    assert "Jak pracujemy" in html
    assert "Rozmowa" in html
    assert "60 lokali" not in html


def test_homepage_contains_business_card(tmp_path, monkeypatch):
    app = _build_public_app_with_legacy_homepage_db(tmp_path, monkeypatch)
    html = app.test_client().get("/").get_data(as_text=True)

    assert "/dla-biznesu" in html
    assert "DLA BIZNESU" in html


def test_navbar_contains_business_link(tmp_path, monkeypatch):
    app = _build_public_app_with_legacy_homepage_db(tmp_path, monkeypatch)
    html = app.test_client().get("/dla-biznesu").get_data(as_text=True)

    assert html.count('href="/dla-biznesu"') >= 2


def test_sitemap_contains_business_solutions(tmp_path, monkeypatch):
    app = _build_public_app_with_legacy_homepage_db(tmp_path, monkeypatch)
    with app.test_request_context("/"):
        urls = build_sitemap_urls(base_url="https://example.test")

    assert any(item["loc"] == "https://example.test/dla-biznesu" for item in urls)


def test_public_regression_smoke(tmp_path, monkeypatch):
    app = _build_public_app_with_legacy_homepage_db(tmp_path, monkeypatch)
    client = app.test_client()
    for path in ["/", "/o-nas", "/franczyza"]:
        resp = client.get(path)
        assert resp.status_code == 200
