#!/usr/bin/env python3
"""Offline synthetic public-job-posting snapshot comparator; no web calls."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Dict, Iterable, List


@dataclass(frozen=True)
class Post:
    provider: str
    endpoint: str
    company_scope: str
    locale: str
    filter_fingerprint: str
    snapshot_complete: bool
    post_id: str
    job_id: str | None
    title: str
    location: str
    body_fingerprint: str
    updated_at: str | None = None
    first_published: str | None = None


def _index(posts: Iterable[Post]) -> Dict[str, Post]:
    indexed: Dict[str, Post] = {}
    for post in posts:
        required = (post.provider, post.endpoint, post.company_scope, post.locale,
                    post.filter_fingerprint, post.post_id, post.title,
                    post.location, post.body_fingerprint)
        valid_strings = all(isinstance(value, str) and value.strip() for value in required)
        valid_job_id = post.job_id is None or (isinstance(post.job_id, str) and post.job_id.strip())
        if not valid_strings or not valid_job_id or post.post_id in indexed:
            raise ValueError("HOLD: missing/invalid field or duplicate post_id")
        indexed[post.post_id] = post
    return indexed


def compare(before: List[Post] | None, after: List[Post] | None) -> List[str]:
    """Return conservative review labels; snapshot omission is never a hire signal."""
    if before is None or after is None:
        return ["missing_snapshot=UNKNOWN — obtain both complete snapshots"]
    if not before or not after:
        return ["missing_snapshot=UNKNOWN — empty snapshot cannot establish a change"]
    before_by_post, after_by_post = _index(before), _index(after)
    anchor = before[0]
    if not all(p.snapshot_complete is True for p in before + after):
        return ["missing_or_partial_snapshot=UNKNOWN — do not infer a filled role, closure, or hiring change"]
    if any(
        (p.provider, p.endpoint, p.company_scope, p.locale,
         p.filter_fingerprint, p.snapshot_complete)
        != (anchor.provider, anchor.endpoint, anchor.company_scope, anchor.locale,
            anchor.filter_fingerprint, True)
        for p in before + after
    ):
        return ["snapshot_context=UNKNOWN — freeze provider, company scope, filters and complete pagination"]

    labels: List[str] = []
    for post_id in sorted(set(before_by_post) & set(after_by_post)):
        old, new = before_by_post[post_id], after_by_post[post_id]
        if old.job_id != new.job_id:
            labels.append(f"identity_conflict=UNKNOWN — post {post_id} has changed job identity")
            continue
        if (old.title, old.location, old.body_fingerprint) != (new.title, new.location, new.body_fingerprint):
            labels.append(f"same_post_edit=REVIEW — post {post_id}; not a newly observed vacancy")

    old_job_posts: Dict[str, set[str]] = {}
    for p in before:
        if p.job_id:
            old_job_posts.setdefault(p.job_id, set()).add(p.post_id)
    for post_id in sorted(set(after_by_post) - set(before_by_post)):
        new = after_by_post[post_id]
        if new.job_id and new.job_id in old_job_posts:
            labels.append(f"possible_repost=REVIEW — new post {post_id} shares job {new.job_id}; human review required")
        else:
            labels.append(f"newly_observed_post=REVIEW — post {post_id}; first_seen is not publication or growth")

    for post_id in sorted(set(before_by_post) - set(after_by_post)):
        labels.append(f"absent_post=UNKNOWN — post {post_id} is absent; do not infer a filled role or closure")

    after_job_counts: Dict[str, int] = {}
    for p in after:
        if p.job_id:
            after_job_counts[p.job_id] = after_job_counts.get(p.job_id, 0) + 1
    for job_id in sorted(job_id for job_id, count in after_job_counts.items() if count > 1):
        labels.append(f"multiple_posts_one_job=REVIEW — job {job_id}; do not count posts as openings")
    if not labels:
        labels.append("no_classified_change=NO_ACTION — unchanged synthetic fields; human source review still required")
    return labels


def fixture_before() -> List[Post]:
    return [
        Post("greenhouse_list", "list", "Northstar public board", "en-US", "all-posted-roles-v1", True, "p-100", "j-10", "Data Analyst", "Remote", "a", "2026-11-01T09:00:00Z"),
        Post("greenhouse_list", "list", "Northstar public board", "en-US", "all-posted-roles-v1", True, "p-200", "j-20", "Support Engineer", "London", "b", "2026-11-01T09:00:00Z"),
    ]


def fixture() -> List[str]:
    before = fixture_before()
    after = [
        Post("greenhouse_list", "list", "Northstar public board", "en-US", "all-posted-roles-v1", True, "p-100", "j-10", "Data Analyst", "Remote", "a2", "2026-11-02T09:00:00Z"),
        Post("greenhouse_list", "list", "Northstar public board", "en-US", "all-posted-roles-v1", True, "p-200", "j-20", "Support Engineer", "London", "b", "2026-11-01T09:00:00Z"),
        Post("greenhouse_list", "list", "Northstar public board", "en-US", "all-posted-roles-v1", True, "p-201", "j-20", "Support Engineer", "London", "b", "2026-11-02T09:00:00Z"),
        Post("greenhouse_list", "list", "Northstar public board", "en-US", "all-posted-roles-v1", True, "p-300", None, "Research Ops", "New York", "c", "2026-11-02T09:00:00Z"),
    ]
    return compare(before, after)


def main() -> None:
    print("offline_synthetic_company_hiring_signal_review")
    print("network_requests=0")
    for line in fixture():
        print(line)
    partial = [Post("greenhouse_list", "list", "Northstar public board", "en-US", "all-posted-roles-v1", False, "p-x", None, "X", "X", "x")]
    print(compare(fixture_before(), partial)[0])
    print("human_review=required — role link is research context, not outreach or payment proof")


if __name__ == "__main__":
    main()
