#!/usr/bin/env python3
"""M3: actual engine services, synthetic fixtures, disposable SQLite, no network/money."""
import argparse
import asyncio
import copy
import importlib.util
import json
from pathlib import Path
import socket
import subprocess
import sys
from datetime import datetime, timezone

PIN = "61c230e1aaa69c125327f08920c49ae127039ef5"


def blocked(*args, **kwargs):
    raise RuntimeError("This example forbids all external network connections")


async def run(backend):
    from fastapi import HTTPException
    from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
    from app.auth.internal import OutcomeInternalCaller
    from app.config import get_settings
    from app.models.base import Base
    from app.models.outcome_verification import OutcomeEvidenceEvent, OutcomeSubjectFact, OutcomeVerificationDecision
    from app.schemas.outcome_verification import OutcomeEvidenceCreateRequest, OutcomeDecisionCreateRequest
    from app.services.outcome_verification import OutcomeVerificationService
    from app.services.outcome_export import OutcomeExportService, compute_content_hash
    from app.services.outcome_policy import PINNED_POLICY_ID

    # No signing credential is accepted or produced by this demonstration.
    get_settings().outcome_proof_pack_hmac_key = ""
    get_settings().outcome_proof_pack_hmac_key_id = ""
    engine = create_async_engine("sqlite+aiosqlite:///:memory:")
    tables = [OutcomeEvidenceEvent.__table__, OutcomeVerificationDecision.__table__, OutcomeSubjectFact.__table__]
    async with engine.begin() as connection:
        await connection.run_sync(Base.metadata.create_all, tables=tables)
    factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    now = datetime.now(timezone.utc)
    caller = OutcomeInternalCaller(caller_id="synthetic-example-verifier", enforced=True,
        subject_types=frozenset({"mission"}), source_apps=frozenset({"server"}),
        may_issue_rewards=False, may_assert_verified=True, sponsor_account_ids=frozenset(), policy_ids=frozenset())
    result = {"schema": "arcus-local-evidence-example.v1", "source_revision": PIN,
        "observed_at": now.isoformat(), "evidence_kind": "synthetic_local_behavior",
        "environment": "disposable SQLite in memory; external connections blocked",
        "limits": ["No physical arrival, field accuracy, provider, deployed API or customer is verified.",
                   "Program eligibility and evidence permission are explicit local fixtures, not a production enrollment test.",
                   "The authorized effect is a local read-only proof-pack export. No reward or payment is attempted.",
                   "The receipt has a SHA-256 integrity seal and is unsigned; no Ed25519 claim is made."]}
    try:
        async with factory() as db:
            # Explicit fixture eligibility precedes any effect. A no-permission
            # fixture is refused before engine ingestion, not called verified.
            permitted, eligible, export_authorized = True, True, True
            if not (permitted and eligible):
                raise RuntimeError("Fixture not permitted and eligible")
            service = OutcomeVerificationService(db)
            evidence_ids = []
            for index, confidence in enumerate([0.91, 0.88]):
                evidence, duplicate = await service.record_evidence(user_id=1, body=OutcomeEvidenceCreateRequest(
                    client_event_id=f"synthetic-m3-{index}", source_app="server", subject_type="mission",
                    subject_id="synthetic-session-1", event_type="mission.status.arrived", occurred_at=now,
                    capture_confidence=confidence, evidence_payload={"synthetic": True, "fixture_permission": "example-only"}))
                assert duplicate is False
                evidence_ids.append(evidence.id)
            body = OutcomeDecisionCreateRequest(user_id=1,subject_type="mission",subject_id="synthetic-session-1",
                decision_type="arrival",status="verified",confidence=0.99,policy_version="untrusted-request-value",
                evidence_event_ids=evidence_ids, reason_codes=["synthetic_policy_test"], decided_at=now,
                decision_key="synthetic-m3-policy-decision")
            evaluated = await service.prepare_mandated_decision(body,caller)
            assert evaluated.policy_version == PINNED_POLICY_ID
            assert evaluated.confidence == 0.88
            decision, duplicate = await service.create_decision(evaluated)
            fact = await service.subject_fact(subject_type="mission",subject_id="synthetic-session-1")
            assert fact is not None and fact.status == "verified" and duplicate is False
            if not export_authorized:
                raise RuntimeError("No export authority")
            pack = await OutcomeExportService(db).build_proof_pack(subject_type="mission",subject_id="synthetic-session-1")
            assert pack is not None
            assert pack["integrity"]["content_hash"] == compute_content_hash(pack)
            assert "signature" not in pack["integrity"]
            tampered = copy.deepcopy(pack)
            tampered["items"][0]["evidence"]["payload"]["synthetic"] = False
            assert compute_content_hash(tampered) != pack["integrity"]["content_hash"]
            wrong_scope = body.model_copy(update={"subject_id":"another-synthetic-session"})
            try:
                await service.prepare_mandated_decision(wrong_scope,caller)
                raise AssertionError("Wrong-subject evidence unexpectedly accepted")
            except HTTPException as exc:
                assert exc.status_code == 403
            result.update({"chain": [
                {"step":"permitted evidence","kind":"explicit synthetic permission fixture; actual record_evidence service","records":2},
                {"step":"eligibility","kind":"explicit synthetic eligible cohort fixture","eligible":eligible},
                {"step":"policy evaluation","policy":evaluated.policy_version,"confidence":evaluated.confidence},
                {"step":"verified fact","kind":"actual persisted engine projection; synthetic inputs","status":fact.status},
                {"step":"authorized action","kind":"explicit local read-only export mandate","money_moved":False},
                {"step":"receipt","kind":"actual proof-pack.v1 export","signed":False,"integrity":"sha256"}],
                "checks":{"pinned_policy_overrode_request":True,"wrong_subject_rejected":True,
                          "stored_fact_matches_decision":True,"receipt_hash_valid":True,"tamper_detected":True},
                "proof_pack":pack})
            await db.rollback()
    finally:
        await engine.dispose()
    return result


if __name__ == "__main__":
    if sys.flags.optimize:
        raise SystemExit("Refusing optimized Python: this example requires assertions. Unset PYTHONOPTIMIZE and run without -O or -OO.")
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--backend",type=Path,required=True)
    parser.add_argument("--output",type=Path,required=True)
    args=parser.parse_args()
    backend=args.backend.resolve()
    revision=subprocess.check_output(["git","-C",str(backend),"rev-parse","HEAD"],text=True).strip()
    if revision!=PIN:
        raise SystemExit("Refusing unpinned backend source: "+revision)
    subprocess.run(["git","-C",str(backend),"diff","--exit-code","HEAD","--","app","tests/contracts/outcome_event"],check=True)
    sys.path.insert(0,str(backend))
    # There is no HTTP client or production database in this example. Refuse
    # accidental network access even if an imported dependency tries to connect.
    socket.create_connection=blocked
    socket.socket.connect=blocked
    output=asyncio.run(run(backend))
    args.output.parent.mkdir(parents=True,exist_ok=True)
    args.output.write_text(json.dumps(output,indent=2,default=str,allow_nan=False)+"\n")
    print("PASS actual local evidence/policy/fact/export chain; synthetic inputs; no money or network")
