"""Read-only opportunity preparation over explicitly sourced public observations.

No network, credentials, account, upload, signature, or submission capability.
The fixture-independent input contract lets a host supply official-source observations.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date, datetime, timezone
import math
from enum import Enum
from typing import Any, Iterable
from urllib.parse import urlsplit
import argparse
import json


class Family(str, Enum):
    PROCUREMENT = "procurement"
    RESEARCH_COMPUTE = "research_compute"


class Eligibility(str, Enum):
    UNKNOWN = "unknown"
    NOT_ELIGIBLE = "not_eligible"
    CRITERIA_MET = "known_criteria_met"


def timestamp(value: str) -> datetime:
    result = datetime.fromisoformat(value.replace("Z", "+00:00"))
    if result.tzinfo is None:
        raise ValueError("Timestamp must include a UTC offset")
    return result


def official_url(value: str) -> str:
    url = urlsplit(value)
    host = (url.hostname or "").lower()
    trusted = host.endswith(".gov") or host.endswith(".mil") or host in {
        "access-ci.org", "allocations.access-ci.org", "support.access-ci.org"
    }
    if url.scheme != "https" or not trusted or url.username or url.password or url.port:
        raise ValueError("Use an HTTPS official source URL without credentials or a port")
    if url.query or url.fragment:
        raise ValueError("Source URLs must omit queries and fragments")
    return value


@dataclass(frozen=True)
class Requirement:
    key: str
    label: str
    source_url: str


@dataclass(frozen=True)
class Opportunity:
    id: str
    family: Family
    title: str
    notice_type: str
    source_url: str
    source_quality: str
    checked_at: str
    deadline_raw: str
    deadline_at: str | None
    deadline_timezone: str | None
    opens_on: str | None
    amendment: str
    amendment_reviewed: bool
    requirements_complete: bool
    requirements: tuple[Requirement, ...]
    required_documents: tuple[str, ...]
    documents_complete: bool
    next_action: str

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> Opportunity:
        data = dict(data)
        for field in ("id", "title", "notice_type", "source_url", "source_quality", "checked_at", "deadline_raw", "amendment", "next_action"):
            if not isinstance(data.get(field), str) or not data[field].strip():
                raise ValueError(f"{field} must be a nonempty string")
        for field in ("deadline_at", "deadline_timezone", "opens_on"):
            if data.get(field) is not None and not isinstance(data[field], str):
                raise ValueError(f"{field} must be string or null")
        if data.get("opens_on") is not None:
            if date.fromisoformat(data["opens_on"]).isoformat() != data["opens_on"]:
                raise ValueError("opens_on must be an ISO calendar date")
        if not isinstance(data.get("requirements"), list) or not isinstance(data.get("required_documents"), list):
            raise ValueError("Requirements and documents must be arrays")
        if any(not isinstance(doc, str) or not doc.strip() for doc in data["required_documents"]):
            raise ValueError("Document labels must be nonempty strings")
        data["family"] = Family(data["family"])
        official_url(data["source_url"])
        timestamp(data["checked_at"])
        if data["source_quality"] not in {"official_page", "official_search_index"}:
            raise ValueError("Unknown source quality")
        if data["deadline_at"]:
            timestamp(data["deadline_at"])
            if not data["deadline_timezone"]:
                raise ValueError("Exact deadline requires original timezone")
        for field in ("amendment_reviewed", "requirements_complete", "documents_complete"):
            if type(data[field]) is not bool:
                raise ValueError(f"{field} must be boolean")
        requirements = []
        seen = set()
        for value in data["requirements"]:
            item = Requirement(**value)
            if not isinstance(item.key, str) or not item.key.strip() or not isinstance(item.label, str) or not item.label.strip():
                raise ValueError("Requirement key and label must be nonempty strings")
            if item.key in seen:
                raise ValueError("Duplicate requirement key")
            seen.add(item.key)
            official_url(item.source_url)
            requirements.append(item)
        data["requirements"] = tuple(requirements)
        data["required_documents"] = tuple(data["required_documents"])
        return cls(**data)


def load_records(path: str) -> list[Opportunity]:
    with open(path, encoding="utf-8") as handle:
        records = [Opportunity.from_dict(item) for item in json.load(handle)]
    if len({item.id for item in records}) != len(records):
        raise ValueError("Duplicate opportunity ID")
    return records


def discover(records: Iterable[Opportunity], family: Family, query: str = "") -> list[Opportunity]:
    """Filter supplied observations; does not claim to search the live internet."""
    terms = query.casefold().split()
    return [r for r in records if r.family == family and
            all(t in f"{r.title} {r.notice_type}".casefold() for t in terms)]


def assess(record: Opportunity, facts: dict[str, bool | None], *, now: str,
           max_age_hours: float = 24) -> dict[str, Any]:
    """Evaluate explicit prerequisite facts. Never turns unknown into false or approval."""
    if not isinstance(facts, dict):
        raise ValueError("Facts must be a JSON object")
    if isinstance(max_age_hours, bool) or not isinstance(max_age_hours, (float,int)) or not math.isfinite(max_age_hours) or max_age_hours <= 0:
        raise ValueError("Freshness limit must be positive")
    if any(value is not None and type(value) is not bool for value in facts.values()):
        raise ValueError("Facts must be true, false, or null; no identity or credential fields")
    current, checked = timestamp(now), timestamp(record.checked_at)
    if checked > current:
        raise ValueError("Check timestamp is in the future")
    missing = [r.label for r in record.requirements if facts.get(r.key) is None]
    failed = [r.label for r in record.requirements if facts.get(r.key) is False]
    eligibility = Eligibility.NOT_ELIGIBLE if failed else (
        Eligibility.UNKNOWN if missing or not record.requirements_complete else Eligibility.CRITERIA_MET)
    blockers = []
    if record.source_quality != "official_page":
        blockers.append("Open and inspect the authoritative notice and attachments")
    if (current - checked).total_seconds() > max_age_hours * 3600:
        blockers.append("Recheck source freshness")
    if not record.amendment_reviewed:
        blockers.append("Review current amendments")
    if not record.requirements_complete:
        blockers.append("Complete eligibility extraction")
    if not record.documents_complete:
        blockers.append("Complete required-document extraction")
    if record.opens_on and current.date() < date.fromisoformat(record.opens_on):
        blockers.append("Request window has not opened")
    if record.deadline_at and timestamp(record.deadline_at) <= current:
        blockers.append("Recorded deadline passed; verify any extension")
    elif record.deadline_at is None and record.deadline_raw != "Rolling":
        blockers.append("Verify deadline clock time and timezone")
    if missing:
        blockers.append("Confirm missing applicant facts")
    decision = "no_bid_known_requirement_failed" if failed else "hold_for_review"
    if not failed and not blockers:
        decision = "ready_for_human_decision"
    return {"id": record.id, "family": record.family.value, "as_of": now,
            "eligibility": eligibility.value, "failed_requirements": failed,
            "unknown_requirements": missing, "decision": decision, "blockers": blockers,
            "next_action": record.next_action, "submission_authorized": False}


def compare(before: Opportunity, after: Opportunity) -> dict[str, Any]:
    if before.id != after.id or before.family != after.family:
        raise ValueError("Compare versions of the same opportunity and family")
    fields = ("title", "notice_type", "source_url", "source_quality", "deadline_raw",
              "deadline_at", "deadline_timezone", "opens_on", "amendment", "requirements",
              "required_documents", "requirements_complete", "documents_complete")
    changed = [field for field in fields if getattr(before, field) != getattr(after, field)]
    return {"id": before.id, "changed_fields": changed,
            "recheck_eligibility_and_documents": bool(changed),
            "before_checked_at": before.checked_at, "after_checked_at": after.checked_at}


def document_check(record: Opportunity, reviewed_documents: dict[str, bool]) -> dict[str, Any]:
    """Require a JSON object of document labels to explicit boolean review flags."""
    if not isinstance(reviewed_documents, dict):
        raise ValueError("Document review flags must be a JSON object")
    if any(not isinstance(key, str) for key in reviewed_documents):
        raise ValueError("Document review keys must be strings")
    if any(type(value) is not bool for value in reviewed_documents.values()):
        raise ValueError("Document review values must be boolean")
    missing = [doc for doc in record.required_documents if not reviewed_documents.get(doc, False)]
    return {"id": record.id, "missing_or_unreviewed": missing,
            "requirements_extraction_complete": record.documents_complete,
            "checklist_complete": record.documents_complete and not missing,
            "content_validated_by_tool": False,
            "note": "Checklist evidence only. The tool does not inspect or upload documents."}


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("records")
    parser.add_argument("command", choices=["discover", "assess", "documents"])
    parser.add_argument("--family", choices=[x.value for x in Family])
    parser.add_argument("--query", default="")
    parser.add_argument("--facts", help="JSON object of non-sensitive boolean facts")
    parser.add_argument("--reviewed-documents", help="JSON object of document review flags")
    parser.add_argument("--now", default=datetime.now(timezone.utc).isoformat())
    args = parser.parse_args()
    records = load_records(args.records)
    if args.family:
        records = discover(records, Family(args.family), args.query)
    elif args.query:
        parser.error("--query requires --family")
    if args.command == "discover":
        result = [{"id": r.id, "title": r.title, "family": r.family.value,
                   "source_url": r.source_url, "source_quality": r.source_quality} for r in records]
    elif args.command == "assess":
        facts = json.loads(args.facts or "{}")
        result = [assess(r, facts, now=args.now) for r in records]
    else:
        flags = json.loads(args.reviewed_documents or "{}")
        result = [document_check(r, flags) for r in records]
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()
