"""Classify the 9 zillow deals (status='new') manually."""
from __future__ import annotations
import io, sys, time
from pathlib import Path

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))

import data_fetchers  # noqa: F401

from deals_db import list_deals, update_classification, init_db
from deal_classifier import classify_deal

init_db()

# Get zillow deals with status='new'
zd = list_deals(source="zillow", status="new", limit=20)
print(f"Zillow deals with status=new: {len(zd)}")

if zd:
    print("Classifying...")
    t0 = time.perf_counter()
    for d in zd:
        result = classify_deal(d)
        update_classification(
            deal_id=d["id"],
            status=result["classification_status"],
            score=result["score"],
            reasons=result["reasons"],
            strategy=result["strategy"],
        )
        addr = (d.get("address") or "?")[:55]
        print(f"  ${d.get('listing_price'):>11,.0f} | score={result['score']:>3} {result['classification_status']:<19} {result['strategy']:<14} | {addr}")
    elapsed = time.perf_counter() - t0
    print(f"\nClassified {len(zd)} deals in {elapsed:.1f}s ({elapsed/len(zd):.1f}s/deal avg)")

# Show final state
print()
print("=== Final Zillow deals state ===")
zd_all = list_deals(source="zillow", limit=20)
for d in zd_all:
    addr = (d.get("address") or "?")[:55]
    score = d.get("classification_score")
    cls = d.get("classification_status") or "?"
    strat = d.get("classification_strategy") or "?"
    price = d.get("listing_price") or 0
    print(f"  ${price:>11,.0f} | score={score!s:>3} {cls:<19} {strat:<14} | {addr}")
