"""Diagnose IMV API behavior for a specific address.

Usage:
    python scripts/probe-imv-by-address.py "Свердловская область, г. Екатеринбург, Склад, ул. Заводская, д. 44-а"

Prints: raw API response, error category, cleaned-address retry result.
"""
import asyncio
import logging
import sys

logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(message)s")


async def main(address: str) -> None:
    from app.services.scrapers.avito_imv import (
        IMVAddressNotFoundError,
        IMVAuthError,
        IMVTransientError,
        evaluate_via_imv,
    )

    # Default params for ЕКБ 3-room 60м²
    params = dict(
        rooms=3,
        area_m2=60.0,
        floor=5,
        floor_at_home=17,
        house_type="panel",
        renovation_type="cosmetic",
        has_balcony=False,
        has_loggia=False,
    )

    print(f"\n=== Attempt 1: original address ===\n{address}\n")
    try:
        result = await evaluate_via_imv(address=address, **params)  # type: ignore[arg-type]
        print(f"OK: recommended={result.recommended_price}")
        return
    except IMVAddressNotFoundError as e:
        print(f"FAIL: address not found (IMVAddressNotFoundError): {e}")
    except IMVAuthError as e:
        print(f"FAIL: auth/quota error (IMVAuthError): {e}")
        return
    except IMVTransientError as e:
        print(f"FAIL: transient/network error (IMVTransientError): {e}")
        return
    except Exception as e:
        print(f"FAIL: {type(e).__name__}: {e}")
        return

    import re

    cleaned = re.sub(
        r"(Склад|Гараж|Подсобка|Нежилое|Помещение|Цех),\s*",
        "",
        address,
        flags=re.IGNORECASE,
    )
    if cleaned != address:
        print(f"\n=== Attempt 2: cleaned address ===\n{cleaned}\n")
        try:
            result = await evaluate_via_imv(address=cleaned, **params)  # type: ignore[arg-type]
            print(f"OK on retry: recommended={result.recommended_price}")
        except IMVAddressNotFoundError as e:
            print(f"FAIL on retry (IMVAddressNotFoundError): {e}")
        except IMVAuthError as e:
            print(f"FAIL on retry (IMVAuthError — quota/auth): {e}")
        except IMVTransientError as e:
            print(f"FAIL on retry (IMVTransientError — network/5xx): {e}")
        except Exception as e:
            print(f"FAIL on retry: {type(e).__name__}: {e}")
    else:
        print("\nNo noise prefix found — cleaned address identical, skipping retry.")


if __name__ == "__main__":
    _address = (
        sys.argv[1]
        if len(sys.argv) > 1
        else "Свердловская область, г. Екатеринбург, Склад, ул. Заводская, д. 44-а"
    )
    asyncio.run(main(_address))
