#!/usr/bin/env python3
import argparse
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path

REPO = Path("/home/shire3d/ARMOR")
PRACTICE_STATE = REPO / "data/academy/design_mastery/runtime/practice_state.json"
AUTOPILOT_STATE = REPO / "data/academy/design_mastery/runtime/autopilot_state.json"
EVIDENCE_ROOT = Path("/SHiREVault/SHiREAcademy/Autopilot")
REPORT_ROOT = EVIDENCE_ROOT / "Reports"

def now():
    return datetime.now(timezone.utc).isoformat()

def load(path):
    return json.loads(path.read_text(encoding="utf-8"))

def write_atomic(path, payload):
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + ".tmp")
    temporary.write_text(
        json.dumps(payload, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
    )
    temporary.replace(path)

def sha256(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()

def select_skill(practice):
    rows = []
    for skill_id, record in (practice.get("skills") or {}).items():
        if record.get("knowledge_certified") is True:
            continue
        rows.append((
            -int(record.get("successful_attempts") or 0),
            -int(record.get("attempts") or 0),
            skill_id,
            record,
        ))
    if not rows:
        return None, None
    _, _, skill_id, record = sorted(rows)[0]
    return skill_id, record

def initialise():
    practice = load(PRACTICE_STATE)
    skill_id, record = select_skill(practice)

    state = {
        "version": "academy_autopilot_v1",
        "created_at": now(),
        "updated_at": now(),
        "enabled": False,
        "paused": True,
        "activation_required": True,
        "mode": "study_qualify_certify",
        "qualifications_required": 3,
        "qualification_pass_score": 100,
        "counted_certification_after_qualifications": True,
        "counted_execution_enabled": False,
        "forge_unlock_allowed": False,
        "max_consecutive_qualification_failures": 3,
        "max_consecutive_infrastructure_failures": 3,
        "practice_state_sha256_at_initialisation": sha256(PRACTICE_STATE),
        "current_skill": skill_id,
        "current_plan": {
            "skill_id": skill_id,
            "next_action": "study_then_uncounted_qualification_1"
                if skill_id else "academy_complete",
            "existing_counted_attempts":
                int((record or {}).get("attempts") or 0),
            "existing_successful_rounds":
                int((record or {}).get("successful_attempts") or 0),
            "knowledge_certified":
                bool((record or {}).get("knowledge_certified")),
            "forge_allowed":
                bool((record or {}).get("forge_allowed")),
        },
        "skills": {},
        "evidence_root": str(EVIDENCE_ROOT),
        "report_root": str(REPORT_ROOT),
        "stop_conditions": [
            "shirevault_unavailable",
            "three_consecutive_infrastructure_failures",
            "three_consecutive_qualification_failures",
            "professional_review_required",
            "unsafe_or_destructive_action",
            "credential_or_external_action_required",
            "certification_contract_cannot_be_satisfied",
        ],
    }

    EVIDENCE_ROOT.mkdir(parents=True, exist_ok=True)
    REPORT_ROOT.mkdir(parents=True, exist_ok=True)
    write_atomic(AUTOPILOT_STATE, state)
    return state

def status():
    state = load(AUTOPILOT_STATE)
    state["practice_state_sha256_now"] = sha256(PRACTICE_STATE)
    state["practice_state_unchanged_since_initialisation"] = (
        state["practice_state_sha256_now"]
        == state["practice_state_sha256_at_initialisation"]
    )
    return state

def main():
    parser = argparse.ArgumentParser(description="SHiRE Academy Autopilot")
    parser.add_argument("command", choices=("initialize", "status", "plan"))
    args = parser.parse_args()

    if args.command == "initialize":
        payload = initialise()
    else:
        payload = status()
        if args.command == "plan":
            payload = {
                "enabled": payload["enabled"],
                "paused": payload["paused"],
                "current_plan": payload["current_plan"],
                "qualifications_required": payload["qualifications_required"],
                "qualification_pass_score": payload["qualification_pass_score"],
                "counted_execution_enabled":
                    payload["counted_execution_enabled"],
                "forge_unlock_allowed": payload["forge_unlock_allowed"],
                "stop_conditions": payload["stop_conditions"],
                "practice_state_unchanged":
                    payload["practice_state_unchanged_since_initialisation"],
            }

    print(json.dumps(payload, indent=2, sort_keys=True))

if __name__ == "__main__":
    main()
