#!/usr/bin/env python3
"""Prepare two private full-reading packets and a synastry dossier.

This is the operational entry point for the full synastry Skill. It accepts
two private birth profiles, runs the native full-reading engine separately,
then builds the receipt and dossier consumed by the bilingual writing pass.
It deliberately does not write customer prose: that requires a chart reader
to distinguish the two people's evidence and live conditions.
"""

from __future__ import annotations

import argparse
import importlib.util
import json
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from datetime import date, datetime
from pathlib import Path
from typing import Any, Mapping


ROOT = Path(__file__).resolve().parents[3]
ENGINE = ROOT / "scripts" / "jyotish_engine.py"
PRE_WORK_CHECK = ROOT / "scripts" / "pre_work_check.py"
DOSSIER_PATH = Path(__file__).with_name("build_full_synastry_dossier.py")
RECEIPT_PATH = Path(__file__).with_name("validate_full_synastry_packets.py")


def _load_module(name: str, path: Path) -> Any:
    spec = importlib.util.spec_from_file_location(name, path)
    module = importlib.util.module_from_spec(spec)
    assert spec and spec.loader
    spec.loader.exec_module(module)
    return module


_DOSSIER = _load_module("full_synastry_dossier", DOSSIER_PATH)
_RECEIPT = _load_module("full_synastry_receipt", RECEIPT_PATH)


def _private_output_directory(value: str) -> Path:
    path = Path(value).expanduser().resolve()
    try:
        path.relative_to(ROOT)
    except ValueError:
        return path
    raise ValueError("--output-dir must be outside the repository because it contains private birth data")


def _number(profile: Mapping[str, Any], key: str, *, minimum: float, maximum: float) -> float:
    value = profile.get(key)
    if not isinstance(value, (int, float)) or isinstance(value, bool) or not minimum <= float(value) <= maximum:
        raise ValueError(f"{key} must be a number between {minimum} and {maximum}")
    return float(value)


def normalize_profile(profile: Mapping[str, Any]) -> dict[str, Any]:
    """Validate a private birth profile without retaining identity fields."""
    if not isinstance(profile, Mapping):
        raise ValueError("birth profile must be a JSON object")
    birth_date = profile.get("date")
    birth_time = profile.get("time")
    if not isinstance(birth_date, str):
        raise ValueError("date is required as YYYY-MM-DD")
    if not isinstance(birth_time, str):
        raise ValueError("time is required as HH:MM or HH:MM:SS")
    try:
        day = date.fromisoformat(birth_date)
        try:
            parsed_time = datetime.strptime(birth_time, "%H:%M:%S").time()
        except ValueError:
            parsed_time = datetime.strptime(birth_time, "%H:%M").time()
    except ValueError as exc:
        raise ValueError("date/time must use YYYY-MM-DD and HH:MM or HH:MM:SS") from exc
    place = profile.get("place")
    if not isinstance(place, str) or not place.strip():
        raise ValueError("place is required; keep the full birth-place text in the private profile")
    ayanamsa = str(profile.get("ayanamsa", "lahiri")).lower()
    node_mode = str(profile.get("node_mode", "mean")).lower()
    if node_mode not in {"mean", "true"}:
        raise ValueError("node_mode must be mean or true")
    return {
        "year": day.year, "month": day.month, "day": day.day,
        "hour": parsed_time.hour, "minute": parsed_time.minute, "second": parsed_time.second,
        "lat": _number(profile, "latitude", minimum=-90, maximum=90),
        "lon": _number(profile, "longitude", minimum=-180, maximum=180),
        "tz": _number(profile, "timezone", minimum=-14, maximum=14),
        "ayanamsa": ayanamsa, "node_mode": node_mode,
        "gender": profile.get("gender") if profile.get("gender") in {"male", "female"} else None,
    }


def full_reading_command(profile: Mapping[str, Any], *, today: str | None = None) -> list[str]:
    """Build the native command from validated input; never hand-calculate charts."""
    command = [
        sys.executable, str(ENGINE), "full-reading",
        "--year", str(profile["year"]), "--month", str(profile["month"]), "--day", str(profile["day"]),
        "--hour", str(profile["hour"]), "--minute", str(profile["minute"]), "--second", str(profile["second"]),
        "--lat", str(profile["lat"]), "--lon", str(profile["lon"]), "--tz", str(profile["tz"]),
        "--ayanamsa", str(profile["ayanamsa"]), "--node-mode", str(profile["node_mode"]),
    ]
    if profile.get("gender"):
        command.extend(("--gender", str(profile["gender"])))
    if today:
        command.extend(("--today", today, "--transit-date", today))
    return command


def preflight_command() -> list[str]:
    """Use the repository gate before native chart calculation."""
    return [
        sys.executable, str(PRE_WORK_CHECK),
        "--remote-timeout", "8", "--command-timeout", "45",
    ]


def _run_preflight() -> dict[str, Any]:
    completed = subprocess.run(preflight_command(), check=False, capture_output=True, text=True)
    if completed.returncode:
        detail = completed.stderr.strip().splitlines()[-1:] or completed.stdout.strip().splitlines()[-1:]
        raise RuntimeError("synastry preflight failed: " + (detail[0] if detail else "unknown failure"))
    return {
        "status": "passed",
        "command": ["scripts/pre_work_check.py", "--remote-timeout", "8", "--command-timeout", "45"],
    }


def _run_full_reading(profile: Mapping[str, Any], today: str | None) -> dict[str, Any]:
    completed = subprocess.run(full_reading_command(profile, today=today), check=False, capture_output=True, text=True)
    if completed.returncode:
        message = completed.stderr.strip().splitlines()[-1:] or ["native full-reading failed"]
        raise RuntimeError("full-reading failed: " + message[0])
    try:
        result = json.loads(completed.stdout)
    except json.JSONDecodeError as exc:
        raise RuntimeError("full-reading did not return JSON") from exc
    if not isinstance(result, dict):
        raise RuntimeError("full-reading returned a non-object result")
    return result


def prepare_synastry_packets(person_a: Mapping[str, Any], person_b: Mapping[str, Any], *, today: str | None = None) -> dict[str, Any]:
    """Run both native charts concurrently and assemble their private evidence."""
    a, b = normalize_profile(person_a), normalize_profile(person_b)
    if (a["ayanamsa"], a["node_mode"]) != (b["ayanamsa"], b["node_mode"]):
        raise ValueError("both profiles must use the same ayanamsa and node_mode before direct comparison")
    preflight = _run_preflight()
    with ThreadPoolExecutor(max_workers=2) as pool:
        future_a = pool.submit(_run_full_reading, a, today)
        future_b = pool.submit(_run_full_reading, b, today)
        packet_a, packet_b = future_a.result(), future_b.result()
    return {
        "preflight": preflight,
        "person_a": packet_a,
        "person_b": packet_b,
        "execution_receipt": _RECEIPT.build_execution_receipt(packet_a, packet_b),
        "dossier": _DOSSIER.build_full_synastry_dossier(packet_a, packet_b),
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="Prepare private full-synastry evidence from two birth profiles.")
    parser.add_argument("--person-a", required=True, help="Private JSON profile: date, time, place, latitude, longitude, timezone, ayanamsa, node_mode")
    parser.add_argument("--person-b", required=True, help="Private JSON profile: date, time, place, latitude, longitude, timezone, ayanamsa, node_mode")
    parser.add_argument("--output-dir", required=True, help="Private directory outside the repository")
    parser.add_argument("--today", help="Optional historical reference date YYYY-MM-DD; omit for the actual current date")
    args = parser.parse_args()
    if args.today:
        date.fromisoformat(args.today)
    output_dir = _private_output_directory(args.output_dir)
    person_a = json.loads(Path(args.person_a).read_text(encoding="utf-8"))
    person_b = json.loads(Path(args.person_b).read_text(encoding="utf-8"))
    prepared = prepare_synastry_packets(person_a, person_b, today=args.today)
    output_dir.mkdir(parents=True, exist_ok=True)
    for name, value in prepared.items():
        (output_dir / f"{name}.json").write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({
        "status": "prepared", "output_dir": str(output_dir),
        "dossier_status": prepared["dossier"].get("delivery_readiness"),
        "next_step": "Write independent Chinese and English section payloads from dossier.json, then run compose_full_synastry_delivery.py.",
    }, ensure_ascii=False))
    return 0


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