"""Offline worksheet consistency review; never executes submissions or awards a rank."""
import argparse
from decimal import Decimal
from datetime import datetime
import hashlib
import json
import math
from pathlib import Path


DIMENSIONS = ("coding", "debugging", "evaluation", "architecture", "communication")
LEVELS = ("junior", "intermediate", "senior")
WEIGHTS = {
    "junior": (35, 25, 15, 15, 10),
    "intermediate": (25, 25, 20, 20, 10),
    "senior": (15, 20, 20, 30, 15),
}
ADDITIONS = {
    "junior": ("prerequisite_and_career_reports", "personal_bounded_code", "task_trace",
               "diagnosed_fault", "source_claim_review", "reviewer_fresh_condition"),
    "intermediate": ("independent_hygiene_change", "unchanged_baseline_regression",
                     "unknown_effect_reconciliation", "two_practice_modules",
                     "career_scheduling_budget_reports", "release_evaluation_incident_package"),
    "senior": ("capacity_isolation_fencing_code", "specialty_counterexample",
               "capacity_assumptions_and_measurement_plan", "two_adrs",
               "migration_rollback_incident_sequence", "team_component_handoff_review"),
}
EVIDENCE_STATES = ("localEngineering", "realProviderIntegration", "reviewerObservedMock",
                   "productionResponsibility")
BASE_GATES = ("identity", "effect", "truth")
MAX_FILE_BYTES = 8 * 1024 * 1024


def required_artifacts(level):
    return tuple(key for earlier in LEVELS[:LEVELS.index(level) + 1]
                 for key in ADDITIONS[earlier])


def required_gates(level):
    return BASE_GATES + (("seniorIsolationBudgetFencing",) if level == "senior" else ())


def nonempty(value):
    return isinstance(value, str) and bool(value.strip())


def review_time(value):
    if not nonempty(value):
        return False
    try:
        return datetime.fromisoformat(value.replace("Z", "+00:00")).utcoffset() is not None
    except ValueError:
        return False


def review(worksheet, root):
    """Validate declared records and actual bytes, without verifying human claims."""
    issues, checked_files = [], []
    root = Path(root).resolve()

    def issue(code, detail, state="pending"):
        issues.append({"code": code, "detail": detail, "state": state})

    def check_file(record, context):
        if not isinstance(record, dict) or not nonempty(record.get("path")):
            issue("file_record_missing", context)
            return
        name, digest = record["path"], record.get("sha256")
        path = (root / name).resolve()
        if Path(name).is_absolute() or not path.is_relative_to(root):
            issue("file_outside_submission", context, "invalid")
            return
        if not isinstance(digest, str) or len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest):
            issue("file_digest_missing", context)
            return
        if not path.is_file():
            issue("file_missing", context, "failed")
            return
        if path.stat().st_size > MAX_FILE_BYTES:
            issue("file_too_large", context, "invalid")
            return
        actual = hashlib.sha256(path.read_bytes()).hexdigest()
        checked_files.append({"context": context, "path": name, "sha256": actual,
                              "matches": actual == digest})
        if actual != digest:
            issue("file_digest_mismatch", context, "failed")

    if (not isinstance(worksheet, dict) or type(worksheet.get("schemaVersion")) is not int
            or worksheet.get("schemaVersion") != 1 or worksheet.get("worksheetVersion") != 2):
        issue("worksheet_version", "Use the current v2 blank worksheet; retain old observations separately.", "invalid")
        worksheet = worksheet if isinstance(worksheet, dict) else {}
    level = worksheet.get("selectedLevel")
    if level not in LEVELS:
        issue("level_pending", "Select junior, intermediate or senior.")
        level = None
    job = worksheet.get("targetJob")
    job = job if isinstance(job, dict) else {}
    duties = job.get("requiredResponsibilities")
    if not isinstance(duties, list) or not duties or not all(nonempty(v) for v in duties):
        issue("target_responsibilities_pending", "Record the actual target responsibilities before assessment.")
    extra_states = job.get("requiredEvidenceStates", [])
    if not isinstance(extra_states, list) or any(v not in EVIDENCE_STATES for v in extra_states):
        issue("job_evidence_contract", "Unknown required evidence state.", "invalid")
        extra_states = []
    for field in ("reviewer", "assistanceRules"):
        if not nonempty(worksheet.get(field)):
            issue(field + "_pending", field)
    check_file({"path": worksheet.get("learnerPersonalSourcePath"),
                "sha256": worksheet.get("learnerPersonalSourceDigest")}, "personal_source")
    assessment = worksheet.get("assessment")
    if not isinstance(assessment, dict):
        issue("assessment_record", "assessment must be an object.", "invalid")
        assessment = {}
    if not review_time(assessment.get("reviewedAt")):
        issue("review_time_pending", "Record the human review time with timezone.")
    artifacts = assessment.get("artifactPathsAndDigests")
    artifacts = artifacts if isinstance(artifacts, dict) else {}
    scores, total = assessment.get("scores"), None
    if level:
        expected = required_artifacts(level)
        profiles = worksheet.get("profiles")
        profile = profiles.get(level) if isinstance(profiles, dict) else None
        profile = profile if isinstance(profile, dict) else {}
        expected_weights = dict(zip(DIMENSIONS, WEIGHTS[level]))
        expected_minima = {d: w * .6 for d, w in expected_weights.items()}
        if (profile.get("requiredArtifactKeys") != list(expected)
                or profile.get("dimensionWeights") != expected_weights
                or profile.get("dimensionMinima") != expected_minima
                or profile.get("requiredCriticalGates") != list(required_gates(level))):
            issue("profile_contract_changed", "Selected profile differs from the published cumulative policy.", "invalid")
        for key in expected:
            record = artifacts.get(key)
            if not isinstance(record, dict) or record.get("status") != "verified":
                state = "failed" if isinstance(record, dict) and record.get("status") == "failed" else "pending"
                issue("artifact_unverified", key, state)
                continue
            if not nonempty(record.get("scope")):
                issue("artifact_scope_missing", key)
            files = record.get("files")
            if not isinstance(files, list) or not files:
                issue("artifact_files_missing", key)
            else:
                for i, file in enumerate(files):
                    check_file(file, key + ":" + str(i))
        gates = assessment.get("criticalGates", {})
        gates = gates if isinstance(gates, dict) else {}
        for key in required_gates(level):
            if gates.get(key) != "verified":
                issue("critical_gate_unverified", key, "failed" if gates.get(key) == "failed" else "pending")
        if not isinstance(scores, dict) or set(scores) != set(DIMENSIONS):
            issue("scores_pending", "All five human-assessed dimensions are required.")
        else:
            valid = True
            for d, maximum in expected_weights.items():
                score = scores[d]
                if type(score) not in (int, float) or not 0 <= score <= maximum or not math.isfinite(score):
                    issue("score_range", d, "invalid")
                    valid = False
                elif Decimal(str(score)) < Decimal(maximum) * Decimal("0.6"):
                    issue("dimension_below_minimum", d, "failed")
            if valid:
                exact_total = sum(Decimal(str(scores[d])) for d in DIMENSIONS)
                total = float(exact_total)
                if exact_total < Decimal(80):
                    issue("total_below_minimum", str(total), "failed")
        reasons = assessment.get("scoreReasons", [])
        reasons = reasons if isinstance(reasons, list) else []
        for d in DIMENSIONS:
            matched = [r for r in reasons if isinstance(r, dict) and r.get("dimension") == d]
            if len(matched) != 1:
                issue("score_reason_pending", d)
                continue
            reason = matched[0]
            keys = reason.get("artifactKeys")
            if (not isinstance(keys, list) or not keys or any(k not in expected for k in keys)
                    or not all(nonempty(reason.get(k)) for k in ("observation", "counterexample", "unverified"))):
                issue("score_reason_incomplete", d)
    fresh = assessment.get("freshCompleteInputAndContract")
    if (not isinstance(fresh, dict)
            or not level or fresh.get("assessedLevel") != level
            or not all(nonempty(fresh.get(k)) for k in ("requirementId", "contract", "positiveCase", "negativeCase", "observation"))
            or not isinstance(fresh.get("inputs"), (dict, list)) or not fresh["inputs"]
            or not isinstance(fresh.get("unchangedRegression"), list) or not fresh["unchangedRegression"]
            or not all(nonempty(x) for x in fresh["unchangedRegression"])):
        issue("fresh_condition_pending", "Record the complete new input, contract, opposite cases, regression and observed change.")
    if not nonempty(assessment.get("observedPersonalChanges")):
        issue("personal_change_observation_pending", "Record the actual changed call site and observed reasoning.")
    states = assessment.get("evidenceStates", {})
    states = states if isinstance(states, dict) else {}
    for key in dict.fromkeys(("localEngineering", "reviewerObservedMock") + tuple(extra_states)):
        state = states.get(key)
        if not isinstance(state, dict) or state.get("status") != "verified" or not nonempty(state.get("scope")):
            issue("required_evidence_pending", key, "failed" if isinstance(state, dict) and state.get("status") == "failed" else "pending")
    invalid = any(x["state"] == "invalid" for x in issues)
    result = {"kind": "worksheet_consistency_only", "selectedLevel": level,
              "requiredArtifactKeys": list(required_artifacts(level)) if level else [],
              "requiredCriticalGates": list(required_gates(level)) if level else [],
              "declaredScoreTotal": total, "checkedFiles": checked_files, "issues": issues,
              "consistencyPassed": not issues,
              "learnerAbilityVerifiedByThisTool": False, "employerReadinessCertified": False,
              "limit": "Checks declared records and file hashes. Human identity, authorship, behavior, source support, provider origin and job fit require independent review.",
              "exitCode": 2 if invalid else (1 if issues else 0)}
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--assessment", required=True)
    parser.add_argument("--root", help="Submission directory; defaults to the worksheet's parent.")
    parser.add_argument("--out", required=True)
    args = parser.parse_args()
    path = Path(args.assessment)
    worksheet = None
    try:
        worksheet = json.loads(path.read_text(encoding="utf-8"), parse_constant=lambda x: (_ for _ in ()).throw(ValueError(x)))
        result = review(worksheet, args.root or path.parent)
    except (OSError, ValueError, TypeError) as exc:
        result = {"kind": "worksheet_consistency_only", "consistencyPassed": False,
                  "learnerAbilityVerifiedByThisTool": False, "employerReadinessCertified": False,
                  "issues": [{"code": "unreadable_or_invalid_record", "detail": type(exc).__name__, "state": "invalid"}], "exitCode": 2}
    output = Path(args.out)
    source_root = Path(args.root or path.parent).resolve()
    protected = [path.resolve()] + [(source_root / x["path"]).resolve() for x in result.get("checkedFiles", [])]
    if isinstance(worksheet, dict):
        records = [{"path": worksheet.get("learnerPersonalSourcePath")}]
        assessment = worksheet.get("assessment")
        artifacts = assessment.get("artifactPathsAndDigests") if isinstance(assessment, dict) else None
        for artifact in artifacts.values() if isinstance(artifacts, dict) else []:
            files = artifact.get("files") if isinstance(artifact, dict) else None
            records.extend(files if isinstance(files, list) else [])
        for record in records:
            if isinstance(record, dict) and nonempty(record.get("path")):
                try:
                    protected.append((source_root / record["path"]).resolve())
                except (OSError, ValueError):
                    pass
    if output.resolve() in protected:
        parser.error("The report must not overwrite the worksheet or a checked submission file.")
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({k: result[k] for k in ("kind", "consistencyPassed", "exitCode")}, ensure_ascii=False))
    return result["exitCode"]


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