#!/usr/bin/env python3
"""Prepare licensing contributions offline, then explicitly send approved fields."""

import argparse
import csv
from datetime import date, datetime, timezone
import hashlib
import hmac
import json
import os
from pathlib import Path
import re
import secrets
import sys
import tempfile
from urllib.error import HTTPError, URLError
from urllib.request import build_opener, HTTPRedirectHandler, Request
import uuid

COUNCILS = frozenset("E06000001 E06000002 E06000003 E06000004 E06000005 E06000006 E06000007 E06000008 E06000009 E06000010 E06000011 E06000012 E06000013 E06000014 E06000015 E06000016 E06000017 E06000018 E06000019 E06000020 E06000021 E06000022 E06000023 E06000024 E06000025 E06000026 E06000027 E06000030 E06000031 E06000032 E06000033 E06000034 E06000035 E06000036 E06000037 E06000038 E06000039 E06000040 E06000041 E06000042 E06000043 E06000044 E06000045 E06000046 E06000047 E06000049 E06000050 E06000051 E06000052 E06000053 E06000054 E06000055 E06000056 E06000057 E06000058 E06000059 E06000060 E06000061 E06000062 E06000063 E06000064 E06000065 E06000066 E07000008 E07000009 E07000010 E07000011 E07000012 E07000032 E07000033 E07000034 E07000035 E07000036 E07000037 E07000038 E07000039 E07000040 E07000041 E07000042 E07000043 E07000044 E07000045 E07000046 E07000047 E07000061 E07000062 E07000063 E07000064 E07000065 E07000066 E07000067 E07000068 E07000069 E07000070 E07000071 E07000072 E07000073 E07000074 E07000075 E07000076 E07000077 E07000078 E07000079 E07000080 E07000081 E07000082 E07000083 E07000084 E07000085 E07000086 E07000087 E07000088 E07000089 E07000090 E07000091 E07000092 E07000093 E07000094 E07000095 E07000096 E07000098 E07000099 E07000102 E07000103 E07000105 E07000106 E07000107 E07000108 E07000109 E07000110 E07000111 E07000112 E07000113 E07000114 E07000115 E07000116 E07000117 E07000118 E07000119 E07000120 E07000121 E07000122 E07000123 E07000124 E07000125 E07000126 E07000127 E07000128 E07000129 E07000130 E07000131 E07000132 E07000133 E07000134 E07000135 E07000136 E07000137 E07000138 E07000139 E07000140 E07000141 E07000142 E07000143 E07000144 E07000145 E07000146 E07000147 E07000148 E07000149 E07000170 E07000171 E07000172 E07000173 E07000174 E07000175 E07000176 E07000177 E07000178 E07000179 E07000180 E07000181 E07000192 E07000193 E07000194 E07000195 E07000196 E07000197 E07000198 E07000199 E07000200 E07000202 E07000203 E07000207 E07000208 E07000209 E07000210 E07000211 E07000212 E07000213 E07000214 E07000215 E07000216 E07000217 E07000218 E07000219 E07000220 E07000221 E07000222 E07000223 E07000224 E07000225 E07000226 E07000227 E07000228 E07000229 E07000234 E07000235 E07000236 E07000237 E07000238 E07000239 E07000240 E07000241 E07000242 E07000243 E07000244 E07000245 E08000001 E08000002 E08000003 E08000004 E08000005 E08000006 E08000007 E08000008 E08000009 E08000010 E08000011 E08000012 E08000013 E08000014 E08000015 E08000017 E08000018 E08000021 E08000022 E08000023 E08000024 E08000025 E08000026 E08000027 E08000028 E08000029 E08000030 E08000031 E08000032 E08000033 E08000034 E08000035 E08000036 E08000037 E08000038 E08000039 E09000001 E09000002 E09000003 E09000004 E09000005 E09000006 E09000007 E09000008 E09000009 E09000010 E09000011 E09000012 E09000013 E09000014 E09000015 E09000016 E09000017 E09000018 E09000019 E09000020 E09000021 E09000022 E09000023 E09000024 E09000025 E09000026 E09000027 E09000028 E09000029 E09000030 E09000031 E09000032 E09000033".split())
AGREEMENT = "lettance-aggregate-outcomes-v1"
ENDPOINT = "https://lettance.com/api/intelligence/v1/outcomes"
FACTS = ("councilGss", "schemeType", "filedOn", "decidedOn", "feePence")
FIELDS = frozenset(("contributionId", *FACTS))
SCHEMES = {"additional_hmo", "mandatory_hmo", "selective"}
FORMAT = "lettance-outcomes-batch-v1"


class Problem(Exception):
    """Only non-sensitive, locally generated messages may reach the console."""


def identifier(value, label, version=None):
    try:
        parsed = uuid.UUID(value)
        if str(parsed) != value.lower() or (version and parsed.version != version):
            raise ValueError
        return str(parsed)
    except (ValueError, AttributeError, TypeError):
        raise Problem("Invalid " + label + ".") from None


def parse_day(value):
    if not isinstance(value, str) or not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", value):
        raise Problem("Use calendar dates in YYYY-MM-DD format.")
    try:
        return date.fromisoformat(value)
    except ValueError:
        raise Problem("Invalid calendar date.") from None


def validate(row, today):
    if not isinstance(row, dict) or set(row) != FIELDS:
        raise Problem("A batch row contains an unexpected or missing field.")
    identifier(row["contributionId"], "contribution UUID", 4)
    if not isinstance(row["councilGss"], str) or row["councilGss"] not in COUNCILS:
        raise Problem("Use a current English council GSS code.")
    if not isinstance(row["schemeType"], str) or row["schemeType"] not in SCHEMES:
        raise Problem("Use selective, additional_hmo or mandatory_hmo.")
    if not parse_day(row["filedOn"]) <= parse_day(row["decidedOn"]) <= today:
        raise Problem("Check the filing and decision dates.")
    if type(row["feePence"]) is not int or not 0 <= row["feePence"] <= 2147483647:
        raise Problem("Use a nonnegative total fee of at most 2147483647 pence.")


def private_file(path, data, replace=False):
    # Publish only a completely written file. Only a progress receipt may be replaced.
    tmp = tempfile.NamedTemporaryFile(dir=path.parent, delete=False)
    try:
        with tmp:
            tmp.write(data)
            tmp.flush()
            os.fsync(tmp.fileno())
        if replace:
            os.replace(tmp.name, path)
        else:
            os.link(tmp.name, path)
    finally:
        if os.path.exists(tmp.name):
            os.unlink(tmp.name)


def local_key(path):
    if not path.exists():
        try:
            private_file(path, secrets.token_bytes(32))
        except FileExistsError:
            pass
    if path.is_symlink() or not path.is_file() or (os.name == "posix" and path.stat().st_mode & 0o077):
        raise Problem("The ID-key file must be a private, regular file.")
    key = path.read_bytes()
    if len(key) != 32:
        raise Problem("Invalid ID-key file. Restore the original to reproduce earlier identifiers.")
    return key


def fee_pence(raw, unit):
    if unit == "gbp":
        if not re.fullmatch(r"[0-9]{1,8}(?:\.[0-9]{1,2})?", raw):
            raise Problem("Use pounds with at most two decimal places and no currency symbols.")
        pounds, _, part = raw.partition(".")
        return int(pounds) * 100 + int(part.ljust(2, "0"))
    if not re.fullmatch(r"[0-9]{1,10}", raw):
        raise Problem("Use whole pence or select --fee-unit gbp.")
    return int(raw)


def load_json(path):
    def unique(pairs):
        result = {}
        for key, value in pairs:
            if key in result:
                raise Problem("Duplicate JSON field.")
            result[key] = value
        return result

    with path.open(encoding="utf-8") as file:
        return json.load(file, object_pairs_hook=unique)


def prepare(args):
    project = identifier(args.project, "project UUID")
    paths = [args.csv, args.id_key, args.out] + ([args.columns] if args.columns else [])
    if len({p.resolve() for p in paths}) != len(paths):
        raise Problem("Use distinct paths for the CSV, mapping, local ID key and output.")
    columns = {"caseId": "caseId", **{k: k for k in FACTS}}
    if args.fee_unit == "gbp":
        columns["feePence"] = "feeGbp"
    if args.columns:
        mapping = load_json(args.columns)
        if (
            not isinstance(mapping, dict)
            or not set(mapping) <= set(columns)
            or not all(isinstance(v, str) and v for v in mapping.values())
        ):
            raise Problem(
                "Invalid column mapping. Only caseId and the five application fact fields can be mapped."
            )
        columns.update(mapping)
    if len(set(columns.values())) != len(columns):
        raise Problem("Map each required field to a distinct CSV column.")
    today = datetime.now(timezone.utc).date()
    key = local_key(args.id_key)
    projected, seen = [], set()
    with args.csv.open(encoding="utf-8-sig", newline="") as file:
        reader = csv.DictReader(file, strict=True)
        headers = reader.fieldnames or []
        if len(set(headers)) != len(headers) or not set(columns.values()) <= set(headers):
            raise Problem("CSV has duplicate headers or lacks a required mapped column.")
        for index, row in enumerate(reader, 1):
            try:
                if None in row or None in row.values():
                    raise Problem("Wrong number of CSV fields.")
                case = row[columns["caseId"]].strip()
                if not case:
                    raise Problem("A stable case ID is required.")
                digest = hmac.new(key, (project + "\0" + case).encode(), hashlib.sha256).digest()
                ident = str(uuid.UUID(bytes=digest[:16], version=4))
                if ident in seen:
                    raise Problem("Duplicate case ID within this batch.")
                seen.add(ident)
                facts = {k: row[columns[k]].strip() for k in FACTS}
                facts["feePence"] = fee_pence(facts["feePence"], args.fee_unit)
                item = {"contributionId": ident, **facts}
                validate(item, today)
                projected.append(item)
            except Problem as error:
                raise Problem(f"CSV record {index}: {error}") from None
    if not projected:
        raise Problem("The CSV contains no completed cases.")
    batch = {"format": FORMAT, "projectId": project, "rows": projected}
    private_file(args.out, (json.dumps(batch, indent=2) + "\n").encode())
    print(f"Prepared {len(projected)} cases locally. Review the output before sending.")


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def request(key, payload=None):
    headers = {"Authorization": "Bearer " + key, "Accept": "application/json"}
    body = None
    if payload is not None:
        headers.update(
            {"Content-Type": "application/json", "X-Lettance-Require-Verified-Contributor": "true"}
        )
        body = json.dumps(payload, separators=(",", ":")).encode()
    req = Request(ENDPOINT, data=body, headers=headers)
    try:
        with build_opener(NoRedirect()).open(req, timeout=30) as response:
            return json.loads(response.read(4096))
    except HTTPError as error:
        retry = error.headers.get("Retry-After", "") if error.headers else ""
        if error.code == 429 and re.fullmatch(r"[0-9]{1,6}", retry):
            raise Problem(f"Lettance returned HTTP 429. Retry after {int(retry)} seconds.") from None
        raise Problem(f"Lettance returned HTTP {error.code}.") from None
    except (OSError, URLError, ValueError):
        raise Problem("Unable to confirm Lettance's response.") from None


def project_key():
    key = os.environ.get("LETTANCE_KEY")
    if not key:
        raise Problem("Set LETTANCE_KEY to a production key with outcomes:write.")
    return key


def show_status():
    status = request(project_key())
    if not isinstance(status, dict) or not isinstance(status.get("verified"), bool):
        raise Problem("Unable to confirm contributor verification.")
    project = identifier(status.get("projectId"), "project UUID")
    print("Project:", project)
    print("Contributor verification:", "verified" if status["verified"] else "not yet verified")


def send(args, transport=request):
    if args.agree != AGREEMENT:
        raise Problem("Sending requires explicit acceptance of the published contribution agreement.")
    batch = load_json(args.batch)
    if (
        not isinstance(batch, dict)
        or set(batch) != {"format", "projectId", "rows"}
        or batch["format"] != FORMAT
    ):
        raise Problem("Choose a prepared Lettance batch.")
    project = identifier(batch["projectId"], "project UUID")
    rows = batch["rows"]
    if not isinstance(rows, list) or not rows:
        raise Problem("Empty or invalid batch.")
    today, seen = datetime.now(timezone.utc).date(), set()
    for index, row in enumerate(rows, 1):
        try:
            validate(row, today)
            if row["contributionId"].lower() in seen:
                raise Problem("Duplicate contribution UUID.")
            seen.add(row["contributionId"].lower())
        except Problem as error:
            raise Problem(f"Batch record {index}: {error}") from None
    key = project_key()
    status = transport(key)
    if (
        not isinstance(status, dict)
        or status.get("projectId") != project
        or status.get("verified") is not True
        or status.get("reuseAgreement") != AGREEMENT
    ):
        raise Problem("The key must belong to this batch's verified project under the current agreement.")
    progress = args.batch.with_name(args.batch.name + ".progress")
    digest = hashlib.sha256(json.dumps(batch, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
    done = 0
    if progress.exists():
        receipt = load_json(progress)
        if not isinstance(receipt, dict) or receipt.get("batchSha256") != digest:
            raise Problem(
                "The saved progress belongs to another batch. Use the original batch or prepare a new file."
            )
        done = receipt.get("confirmed")
        if type(done) is not int or not 0 <= done <= len(rows):
            raise Problem(
                "Invalid saved progress. Keep the batch and restore the receipt or safely replay it without the receipt."
            )
    for index, row in enumerate(rows[done:], done + 1):
        try:
            payload = {field: row[field] for field in FIELDS}
            payload["reuseAgreement"] = AGREEMENT
            receipt = transport(key, payload)
            if (
                not isinstance(receipt, dict)
                or receipt.get("contributionId") != row["contributionId"].lower()
                or receipt.get("state") != "accepted"
            ):
                raise Problem("Unexpected receipt.")
            private_file(
                progress, json.dumps({"batchSha256": digest, "confirmed": index}).encode(), replace=True
            )
        except Problem as error:
            raise Problem(
                f"Stopped at batch record {index}. {error} Earlier confirmed: {index - 1}. Retry the same batch."
            ) from None
    print(f"Lettance confirmed {len(rows)} cases, including any identical retries.")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest="command", required=True)
    local = commands.add_parser("prepare", help="validate and project an export entirely offline")
    local.add_argument("--csv", required=True, type=Path)
    local.add_argument("--project", required=True, help="verified Lettance project UUID")
    local.add_argument(
        "--id-key",
        required=True,
        type=Path,
        help="private local file created once per integration; reuse for every export",
    )
    local.add_argument("--out", required=True, type=Path, help="new private output file")
    local.add_argument("--columns", type=Path, help="optional JSON map from field names to CSV header names")
    local.add_argument("--fee-unit", choices=["pence", "gbp"], default="pence")
    commands.add_parser("status", help="read project ID and verification without sending a case")
    upload = commands.add_parser("send", help="send a reviewed batch to your verified project")
    upload.add_argument("--batch", required=True, type=Path)
    upload.add_argument("--agree", required=True, help="exact agreement version you accept")
    args = parser.parse_args()
    try:
        if args.command == "prepare":
            prepare(args)
        elif args.command == "status":
            show_status()
        else:
            send(args)
    except Problem as error:
        print(str(error), file=sys.stderr)
        return 1
    except FileExistsError:
        print("The output already exists. Choose a new filename or reuse the saved batch.", file=sys.stderr)
        return 1
    except (OSError, ValueError, csv.Error, TypeError):
        print(
            "Could not read or validate the local file or request. Check the file format and permissions.",
            file=sys.stderr,
        )
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
