#!/usr/bin/env python3
"""
Record user verdicts on properties for calibration.

Usage:
    python3 verdict.py <url> yes [--flags liked,needs-info]
    python3 verdict.py <url> no [--flags semi-detached,too-small]
    python3 verdict.py <url> maybe [--flags heavy-renovation]
    python3 verdict.py list                              # Show all verdicts
    python3 verdict.py stats                             # Verdict count + concordance
"""
import argparse
import sys

from store import load, persist, upsert, short_url


def find_property(store, query):
    """Find a property by URL fragment or properstar ID."""
    # Exact match
    if query in store:
        return query
    # Partial URL match
    matches = [url for url in store if query in url]
    if len(matches) == 1:
        return matches[0]
    if len(matches) > 1:
        print(f"Ambiguous query '{query}', matches:")
        for m in matches[:5]:
            print(f"  {short_url(m)}")
        return None
    print(f"No property found matching '{query}'")
    return None


def cmd_record(store, url, verdict, flags):
    """Record a verdict on a property."""
    full_url = find_property(store, url)
    if not full_url:
        return False

    p = store[full_url]
    old_verdict = p.get('user_verdict')

    upsert(store, full_url, {
        'user_verdict': verdict,
        'user_flags': flags if flags else [],
    })

    loc = p.get('location') or p.get('city') or p.get('title', '')
    price = p.get('price')
    price_str = f"EUR {price:,.0f}" if price else '?'

    action = 'Updated' if old_verdict else 'Recorded'
    print(f"{action}: {verdict.upper()} — {loc} ({price_str})")
    if flags:
        print(f"  Flags: {', '.join(flags)}")
    if old_verdict and old_verdict != verdict:
        print(f"  Changed from: {old_verdict}")

    persist(store)
    return True


def cmd_list(store):
    """List all properties with verdicts."""
    verdicts = [(url, p) for url, p in store.items() if p.get('user_verdict')]
    if not verdicts:
        print("No verdicts recorded yet.")
        return

    # Group by verdict
    for group in ['yes', 'maybe', 'no']:
        items = [(url, p) for url, p in verdicts if p.get('user_verdict') == group]
        if not items:
            continue
        print(f"\n  {group.upper()} ({len(items)})")
        print(f"  {'-' * 60}")
        for url, p in items:
            loc = (p.get('location') or p.get('city') or '')[:30]
            price = p.get('price')
            price_str = f"EUR {price:,.0f}" if price else '?'
            flags = ', '.join(p.get('user_flags', []))
            score = p.get('overall_score') or p.get('cp_score') or '?'
            print(f"  {loc:<30} {price_str:>12}  score:{score}  {flags}")

    print(f"\n  Total: {len(verdicts)} verdicts")


def cmd_stats(store):
    """Show verdict statistics and current concordance."""
    verdicts = [(url, p) for url, p in store.items() if p.get('user_verdict')]

    yes_count = sum(1 for _, p in verdicts if p['user_verdict'] == 'yes')
    maybe_count = sum(1 for _, p in verdicts if p['user_verdict'] == 'maybe')
    no_count = sum(1 for _, p in verdicts if p['user_verdict'] == 'no')

    print(f"Verdicts: {len(verdicts)} ({yes_count} yes, {maybe_count} maybe, {no_count} no)")

    if yes_count > 0 and no_count > 0:
        print(f"Run 'python3 calibrate_weights.py' to optimize scoring weights")
    elif len(verdicts) < 10:
        print(f"Need more verdicts for meaningful calibration (have {len(verdicts)}, want 10+)")

    # Common flags
    all_flags = {}
    for _, p in verdicts:
        for flag in p.get('user_flags', []):
            all_flags[flag] = all_flags.get(flag, 0) + 1

    if all_flags:
        print(f"\nCommon flags:")
        for flag, count in sorted(all_flags.items(), key=lambda x: -x[1]):
            print(f"  {flag}: {count}")


def main():
    parser = argparse.ArgumentParser(description='Record property verdicts')
    parser.add_argument('command', help='URL fragment, "list", or "stats"')
    parser.add_argument('verdict', nargs='?', choices=['yes', 'no', 'maybe'],
                        help='Verdict (yes/no/maybe)')
    parser.add_argument('--flags', type=str, default='',
                        help='Comma-separated flags (e.g. semi-detached,too-small)')
    args = parser.parse_args()

    store = load()

    if args.command == 'list':
        cmd_list(store)
    elif args.command == 'stats':
        cmd_stats(store)
    elif args.verdict:
        flags = [f.strip() for f in args.flags.split(',') if f.strip()] if args.flags else []
        cmd_record(store, args.command, args.verdict, flags)
    else:
        print("Usage: verdict.py <url> yes|no|maybe [--flags ...]")
        print("       verdict.py list")
        print("       verdict.py stats")
        sys.exit(1)


if __name__ == '__main__':
    main()
