#!/usr/bin/env python3
"""
Orion Permit Dashboard — web server.
Serves dashboard.html and provides a shared leads API backed by leads.json.

Run:   python3 server.py
Team:  http://<your-Mac-IP>:5000   (find IP: ipconfig getifaddr en0)
"""
import json, os, sys
from flask import Flask, request, jsonify, send_file

app = Flask(__name__)

BASE_DIR   = os.path.dirname(os.path.abspath(__file__))
LEADS_FILE = os.path.join(BASE_DIR, "leads.json")
DASHBOARD  = os.path.join(BASE_DIR, "dashboard.html")

# Load scraper CONFIG for team_members etc. (optional — falls back gracefully)
try:
    sys.path.insert(0, BASE_DIR)
    from scraper_v2 import CONFIG as SCRAPER_CONFIG
except Exception:
    SCRAPER_CONFIG = {}

EMPTY_LEAD = lambda: {"status": "lead", "stage": None, "notes": "",
                       "assigned_to": "", "contacted_date": None, "monday_item_id": None}

def read_leads():
    """Load leads.json, auto-migrating flat {id:'lead'} format to object format."""
    if not os.path.exists(LEADS_FILE):
        return {}
    with open(LEADS_FILE, encoding="utf-8") as f:
        data = json.load(f)
    migrated = {}
    changed = False
    for pid, val in data.items():
        if isinstance(val, str):
            migrated[pid] = {"status": val, "stage": None, "notes": "",
                             "assigned_to": "", "contacted_date": None, "monday_item_id": None}
            changed = True
        else:
            migrated[pid] = val
    if changed:
        write_leads(migrated)
    return migrated

def write_leads(data):
    with open(LEADS_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2)


# ── ROUTES ────────────────────────────────────────────────────────────────────

@app.route("/")
def index():
    return send_file(DASHBOARD)

@app.route("/api/leads", methods=["GET"])
def get_leads():
    return jsonify(read_leads())

@app.route("/api/leads", methods=["POST"])
def post_leads():
    """Full replace — used by the lead toggle (backward compat)."""
    write_leads(request.get_json(force=True))
    return jsonify({"ok": True})

@app.route("/api/leads/<permit_id>", methods=["PATCH"])
def patch_lead(permit_id):
    """Partial update for pipeline fields (stage, notes, assigned_to, contacted_date)."""
    leads = read_leads()
    if permit_id not in leads:
        leads[permit_id] = EMPTY_LEAD()
    updates = request.get_json(force=True) or {}
    leads[permit_id].update(updates)
    write_leads(leads)
    return jsonify({"ok": True, "lead": leads[permit_id]})

@app.route("/api/config", methods=["GET"])
def get_config():
    """Return team configuration for the dashboard."""
    return jsonify({
        "team_members": SCRAPER_CONFIG.get("team_members", []),
        "monday_board_id": SCRAPER_CONFIG.get("monday", {}).get("board_id", ""),
    })


if __name__ == "__main__":
    import socket
    try:
        local_ip = socket.gethostbyname(socket.gethostname())
    except Exception:
        local_ip = "your-Mac-IP"
    print("\n  Orion Permit Dashboard")
    print(f"  Local:   http://localhost:5000")
    print(f"  Network: http://{local_ip}:5000")
    print("\n  Keep this terminal open while the team is using the dashboard.")
    print("  Press Ctrl+C to stop.\n")
    app.run(host="0.0.0.0", port=5000, debug=False)
