import io
import socket
import sqlite3
from contextlib import closing

import pytest
from PIL import Image

from InvestmentManager.export_engine import runtime_paths
from .fixtures import OLD_FOREIGN_OFFERS_SCHEMA, NEW_SCHEMA_MIGRATIONS, FOREIGN_OFFER_SIDE_TABLES, _offer_row


@pytest.fixture(autouse=True)
def no_network(monkeypatch):
    def forbidden(*args, **kwargs):
        raise AssertionError("Network access is forbidden in generator tests")
    monkeypatch.setattr(socket.socket, "connect", forbidden)
    monkeypatch.setattr(socket, "create_connection", forbidden)


@pytest.fixture()
def offer_row():
    return _offer_row


@pytest.fixture()
def data_root(tmp_path):
    root = tmp_path / "InvestmentData"
    (root / "databases").mkdir(parents=True)
    (root / "offers/17").mkdir(parents=True)
    (root / "agents").mkdir()
    for index, color in enumerate([(90, 100, 130), (160, 60, 40)]):
        Image.new("RGB", (64, 48), color).save(root / f"offers/17/image_17_url_{index}.jpg")
    Image.new("RGB", (32, 32), (20, 130, 50)).save(root / "agents/agent_7.jpg")
    (root / "offers/17/description_17.md").write_text("Opis testowy <b>tekst</b>", encoding="utf-8")
    offer = [17, "działka", "sprzedaż", "pierwotny", "Polska", "Warszawa", "Centrum", "191025", "2026-10-25", "aktywna", "1000", "płaska", "prostokąt", "dom wolnostojący", "wolnostojący", "dach płaski", "garaż", "2", "0", "75", "65", "3", "nie", "PCV", "aneks", "miejska", "gazowe", "tak", "tak", "100", "budowlana", "dobry", "usługowe", "dobry", "2025", "7", "Działka testowa"]
    columns = ['ID', 'Typ_nieruchomosci', 'Typ_oferty', 'Typ_rynku', 'Kraj', 'Miejscowosc', 'Lokalizacja', 'Cena', 'Data_dodania', 'Status_oferty', 'Powierzchnia_dzialki', 'Uksztaltowanie_dzialki', 'Ksztalt_dzialki', 'Rodzaj_budynku', 'Typ_domu', 'Typ_dachu', 'Parking', 'Liczba_pieter', 'Pietro', 'Powierzchnia', 'Powierzchnia_uzytkowa', 'Liczba_pokoi', 'Umeblowanie', 'Typ_okien', 'Typ_kuchni', 'Kanalizacja', 'Ogrzewanie', 'Prad', 'Gaz', 'Czynsz_administracyjny', 'Przeznaczenie_dzialki', 'Stan_budynku', 'Przeznaczenie_lokalu', 'Standard', 'Rok_budowy', 'ID_agenta', 'Tytul']
    with closing(sqlite3.connect(root / "databases/IDB.db")) as conn, conn:
        conn.execute("CREATE TABLE EstateData (" + ",".join(f'"{c}" TEXT' for c in columns) + ")")
        conn.execute("INSERT INTO EstateData VALUES (" + ",".join("?" for _ in offer) + ")", offer)
        conn.execute("CREATE TABLE Localization (ID TEXT, Miejscowosc TEXT, Wojewodztwo TEXT, Powiat TEXT, Gmina TEXT, Ulica TEXT)")
        conn.execute("INSERT INTO Localization VALUES ('17','Warszawa','mazowieckie','Warszawa','Warszawa','Testowa')")
    with closing(sqlite3.connect(root / "databases/agents.db")) as conn, conn:
        conn.execute("CREATE TABLE agents_v2 (id INTEGER, login TEXT, password_hash TEXT, access_level TEXT, first_name TEXT, last_name TEXT, email TEXT, phone TEXT, license TEXT, is_active INTEGER)")
        conn.execute("INSERT INTO agents_v2 VALUES (7,'fixture','not-a-real-hash','agent','Jan','Testowy','test@example.invalid','600100200','123',1)")
    with closing(sqlite3.connect(root / "databases/foreign_offers.db")) as conn, conn:
        conn.executescript(OLD_FOREIGN_OFFERS_SCHEMA + NEW_SCHEMA_MIGRATIONS + FOREIGN_OFFER_SIDE_TABLES)
        conn.executescript("ALTER TABLE foreign_developments ADD COLUMN source_platform TEXT; ALTER TABLE foreign_developments ADD COLUMN source_key TEXT;")
        conn.execute("INSERT INTO foreign_developments (id,name,source_platform,source_key) VALUES (7,'Azure Bay','cyprus_constructions','azure-bay')")
        for offer_id in (11, 12, 13):
            conn.execute("""INSERT INTO foreign_offers (id,source_platform,source_url,source_offer_ref,offer_title,offer_description,source_country_name,source_city_name,price_value,price_currency,area_total_m2,rooms_count,is_export_ready,offer_type_normalized,market_type_normalized,category_id_domiporta,property_type_source,floor,development_id,agent_name,agent_email,agent_phone)
                VALUES (?,'cyprus_constructions',?,?,'Azure Bay','Opis & <b>test</b>','Cypr','Kyrenia',191025,'EUR',75,3,1,'sale','primary','191','apartament',0,7,'Jan Testowy','test@example.invalid','600100200')""", (offer_id, f'https://cyprus.example.invalid/project#unit-type={offer_id}', str(offer_id)))
            conn.execute("INSERT INTO foreign_offer_images (foreign_offer_id,image_url,sort_order,is_primary) VALUES (?,?,0,1)", (offer_id, (root / 'offers/17/image_17_url_0.jpg').as_uri()))
            for portal in ("domiporta", "tabelaofert"):
                conn.execute("INSERT INTO foreign_offer_portal_sync (foreign_offer_id,portal_key,is_published,last_action) VALUES (?,?,1,'add')", (offer_id, portal))
        conn.execute("INSERT INTO foreign_offer_export_warnings (foreign_offer_id,warning_code,warning_message,is_blocking) VALUES (12,'source_sold_out','Sold Out',1)")
        conn.execute("UPDATE foreign_offers SET is_export_ready=0 WHERE id=12")
    return root


@pytest.fixture(autouse=True)
def input_context(tmp_path):
    # Pure payload tests also need an explicit base URL, never environment/.env.
    with runtime_paths.use(runtime_paths.LocalInputs(tmp_path)):
        yield


@pytest.fixture()
def export_module():
    from InvestmentManager.export_engine import foreign_offers_export
    return foreign_offers_export
