#!/usr/bin/env python3
"""Verify GBS inserts produce BSON Date fields the Prisma web app expects.

Requires:
  - mongosh on PATH
  - PT_RESEARCH_DATABASE_URI set (e.g. export PT_RESEARCH_DATABASE_URI=$(tr -d '\\n' < .mongodb_uri))

Does not read .mongodb_uri itself; use shell redirection so secrets stay in the environment only.

Run from repo root:
  PT_RESEARCH_DATABASE_URI=$(tr -d '\\n' < .mongodb_uri) uv run python scripts/verify_gbs_bson_shapes.py
"""

from __future__ import annotations

import os
import sys


def main() -> int:
    if not os.environ.get("PT_RESEARCH_DATABASE_URI"):
        print("ERROR: PT_RESEARCH_DATABASE_URI is not set", file=sys.stderr)
        return 1

    # Import after env is set (module reads URI at call time)
    from point_topic_mcp.core import mongodb_utils as m

    ops = m.find_operators()
    if not ops:
        print("ERROR: no operators in database", file=sys.stderr)
        return 1

    op = ops[0]
    oid = m._oid_from_doc(op)
    name = op.get("name", "unknown")
    country = op.get("country", "")
    techs = op.get("technologies") or []
    if not techs:
        print("ERROR: first operator has no technologies", file=sys.stderr)
        return 1
    tech = techs[0]

    stat_doc = {
        "type": "broadband",
        "country": country,
        "operator": name,
        "operatorId": oid,
        "period": "2099Q1",
        "tech": tech,
        "channel": "Infrastructure",
        "domain": "Residential",
        "subscribers": 1,
        "is_estimate": False,
        "restated": False,
        "notes": "__mcp_bson_shape_verify__",
        "createdBy": "verify_gbs_bson_shapes.py",
    }

    sid = m.insert_one_statistic(stat_doc)

    js_stat = f"""
    const s = db.{m.STATISTICS_COLLECTION}.findOne({{_id: ObjectId("{sid}")}});
    if (!s) {{ throw new Error("Statistics not found"); }}
    const ok = (s.date instanceof Date) && (s.createdAt instanceof Date) &&
      (s.updatedAt instanceof Date) && (s.is_archived === false);
    print(ok ? "STATISTICS_OK" : "STATISTICS_FAIL");
    """
    out = m._run_mongosh(js_stat, timeout=30)
    print(out)
    if "STATISTICS_OK" not in out:
        m._run_mongosh(
            f'db.{m.STATISTICS_COLLECTION}.deleteOne({{_id: ObjectId("{sid}")}})',
            timeout=30,
        )
        return 1

    m._run_mongosh(
        f'db.{m.STATISTICS_COLLECTION}.deleteOne({{_id: ObjectId("{sid}")}})',
        timeout=30,
    )

    src_doc = {
        "operatorId": oid,
        "year": 2099,
        "quarter": 1,
        "type": "__mcp_bson_shape_verify__",
        "url": "https://example.com/mcp-bson-verify",
    }
    src_id = m.insert_one_source(src_doc)

    js_src = f"""
    const s = db.{m.SOURCES_COLLECTION}.findOne({{_id: ObjectId("{src_id}")}});
    if (!s) {{ throw new Error("Sources not found"); }}
    const ok = (s.createdAt instanceof Date) && (s.updatedAt instanceof Date);
    print(ok ? "SOURCES_OK" : "SOURCES_FAIL");
    """
    out2 = m._run_mongosh(js_src, timeout=30)
    print(out2)
    m._run_mongosh(
        f'db.{m.SOURCES_COLLECTION}.deleteOne({{_id: ObjectId("{src_id}")}})',
        timeout=30,
    )

    if "SOURCES_OK" not in out2:
        return 1

    print("All BSON shape checks passed (temp docs deleted).")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
