"""Remplit servers.domain_ltd par convention SANEF (2eme lettre du hostname).

Regle:
  v[p|i]* -> sanef.groupe   (prod/integration)
  v[r|t|d]* -> sanef-rec.fr (recette/test/dev)

Applique UNIQUEMENT aux serveurs dont domain_ltd est vide (NULL ou '').

Usage:
    python tools/fill_domain_ltd_by_prefix.py [--dry-run]
"""
import os
import argparse
from sqlalchemy import create_engine, text

DATABASE_URL = os.getenv("DATABASE_URL_DEMO") or os.getenv("DATABASE_URL") \
    or "postgresql://patchcenter:PatchCenter2026!@localhost:5432/patchcenter_demo"

RULES = {
    "p": "sanef.groupe",
    "i": "sanef.groupe",
    "r": "sanef-rec.fr",
    "t": "sanef-rec.fr",
    "d": "sanef-rec.fr",
}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args()

    engine = create_engine(DATABASE_URL)
    print(f"[INFO] DB: {DATABASE_URL.split('@')[-1]}")
    conn = engine.connect().execution_options(isolation_level="AUTOCOMMIT")

    rows = conn.execute(text("""
        SELECT id, hostname FROM servers
        WHERE (domain_ltd IS NULL OR domain_ltd = '')
        ORDER BY hostname
    """)).fetchall()
    print(f"[INFO] {len(rows)} serveurs sans domain_ltd")

    updated = skipped = 0
    for r in rows:
        h = (r.hostname or "").lower()
        if len(h) < 2 or h[0] != "v":
            skipped += 1
            continue
        domain = RULES.get(h[1])
        if not domain:
            skipped += 1
            continue
        if args.dry_run:
            print(f"  DRY: {r.hostname:25s} -> {domain}")
        else:
            conn.execute(text("UPDATE servers SET domain_ltd=:d WHERE id=:sid"),
                         {"d": domain, "sid": r.id})
        updated += 1

    conn.close()
    print(f"\n[DONE] Maj: {updated} | Skip (hors regle): {skipped}")


if __name__ == "__main__":
    main()
