#!/usr/bin/env python3
"""Small, sequential FormKiQ migration example. Python 3.10+, standard library only."""

import argparse
import csv
import hashlib
import json
import os
from pathlib import Path
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from datetime import datetime, timezone

MAX_BYTES = 1024 * 1024
KEYS = ("migrationSampleSourceId", "migrationSampleBatch", "migrationSampleType")
SAMPLES = (
    ("legacy-001", "invoice", "Invoice example: amount 125.00 EUR.\n"),
    ("legacy-002", "policy", "Policy example: review every twelve months.\n"),
    ("legacy-003", "memo", "Memo example: retain the original source identifier.\n"),
)


class MigrationError(Exception):
    pass


class HttpFailure(MigrationError):
    def __init__(self, status):
        self.status = status
        super().__init__(f"HTTP {status}; inspect the record before retrying a write")


class NotReady(MigrationError):
    pass


class NoRedirects(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def digest(data):
    return hashlib.sha256(data).hexdigest()


def save_json(path, value):
    temporary = path.with_suffix(path.suffix + ".tmp")
    temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8")
    temporary.replace(path)


def prepare(directory):
    # A new preparation creates a new batch. Never replace an existing ID mapping.
    directory.mkdir(parents=True, exist_ok=False)
    (directory / "files").mkdir()
    batch = str(uuid.uuid4())
    records = []
    for source_id, kind, text in SAMPLES:
        content = text.encode("utf-8")
        file = f"files/{source_id}.txt"
        (directory / file).write_bytes(content)
        records.append({
            "sourceId": source_id, "documentId": str(uuid.uuid4()),
            "path": f"migration-sample/{batch}/{source_id}.txt",
            "file": file, "contentType": "text/plain", "bytes": len(content),
            "sha256": digest(content),
            "attributes": dict(zip(KEYS, (source_id, batch, kind))),
        })
    save_json(directory / "manifest.json", {"version": 1, "batchId": batch, "records": records})
    tables = {
        "attributes.csv": (["AttributeKey", "DataType", "Type"],
                           [[key, "STRING", "STANDARD"] for key in KEYS]),
        "documents.csv": (["DocumentId", "Path", "ContentType", "DeepLink"],
                          [[r["documentId"], r["path"], r["contentType"], ""] for r in records]),
        "document-attributes.csv": (["DocumentId", "AttributeKey", "StringValue"],
                                    [[r["documentId"], key, value] for r in records
                                     for key, value in r["attributes"].items()]),
        "document-contents.csv": (["DocumentId", "Location"],
                                  [[r["documentId"], str((directory / r["file"]).resolve())]
                                   for r in records]),
    }
    for name, (headers, rows) in tables.items():
        with (directory / name).open("w", newline="", encoding="utf-8") as output:
            writer = csv.writer(output)
            writer.writerow(headers)
            writer.writerows(rows)
    print("Prepared 3 synthetic records, stable document IDs, and four CSV files.")


def read_source(directory, record):
    source = (directory / record["file"]).resolve()
    if not source.is_relative_to(directory.resolve()):
        raise MigrationError("Source file must stay inside the prepared sample directory")
    with source.open("rb") as stream:
        content = stream.read(MAX_BYTES + 1)
    if (len(content) > MAX_BYTES or len(content) != record["bytes"] or
            digest(content) != record["sha256"]):
        raise MigrationError("Source bytes changed or exceed the example's 1 MiB limit")
    return content


def load_manifest(directory):
    raw = (directory / "manifest.json").read_bytes()
    manifest = json.loads(raw)
    if manifest.get("version") != 1 or not manifest.get("records"):
        raise MigrationError("Unsupported or empty sample manifest")
    ids = set()
    sources = set()
    for record in manifest["records"]:
        doc_id = record["documentId"]
        if str(uuid.UUID(doc_id, version=4)) != doc_id or uuid.UUID(doc_id).version != 4:
            raise MigrationError("Document IDs must be UUID v4 values")
        if doc_id in ids or record["sourceId"] in sources:
            raise MigrationError("Duplicate document or source identifier in manifest")
        ids.add(doc_id)
        sources.add(record["sourceId"])
        if (record["attributes"].get(KEYS[0]) != record["sourceId"] or
                record["attributes"].get(KEYS[1]) != manifest["batchId"]):
            raise MigrationError("Sample attributes do not match the source/batch mapping")
        read_source(directory, record)
    return manifest, digest(raw)


def validate_url(url):
    parsed = urllib.parse.urlsplit(url)
    local = parsed.hostname in ("127.0.0.1", "localhost", "::1")
    if (not parsed.hostname or parsed.username or parsed.password or parsed.fragment or
            (parsed.scheme != "https" and not (parsed.scheme == "http" and local))):
        raise MigrationError("Use an HTTPS URL without embedded credentials or fragments")
    return parsed


class Client:
    def __init__(self, base_url, token, site_id):
        parsed = validate_url(base_url)
        if parsed.query or not token or not site_id:
            raise MigrationError("Set the API base URL, JWT token, and site ID")
        self.base_url = base_url.rstrip("/")
        self.token = token
        self.site_id = site_id
        self.opener = urllib.request.build_opener(NoRedirects)

    def request(self, method, url, data=None, authenticated=False, headers=None):
        validate_url(url)
        headers = dict(headers or {})
        if any(key.lower() in ("authorization", "proxy-authorization", "cookie") for key in headers):
            raise MigrationError("Storage headers must not contain authentication or cookies")
        if authenticated:
            headers["Authorization"] = self.token
        if data is not None and not any(key.lower() == "content-type" for key in headers):
            headers["Content-Type"] = "application/json" if authenticated else "application/octet-stream"
        # Reads can retry; writes are attempted once and reconciled on the next run.
        attempts = 4 if method == "GET" else 1
        for attempt in range(attempts):
            try:
                request = urllib.request.Request(url, data=data, headers=headers, method=method)
                with self.opener.open(request, timeout=30) as response:
                    content = response.read(MAX_BYTES + 1)
                if len(content) > MAX_BYTES:
                    raise MigrationError("Response exceeds this small example's 1 MiB limit")
                return content
            except urllib.error.HTTPError as error:
                status = error.code
                error.close()
                if status not in (429, 500, 502, 503, 504) or attempt == attempts - 1:
                    raise HttpFailure(status) from None
            except (urllib.error.URLError, OSError):
                if attempt == attempts - 1:
                    raise MigrationError("Network request failed; no write was automatically replayed") from None
            time.sleep(min(2 ** attempt, 4))

    def api(self, method, path, body=None, query=None):
        parameters = {"siteId": self.site_id, **(query or {})}
        url = self.base_url + path + "?" + urllib.parse.urlencode(parameters)
        payload = json.dumps(body).encode("utf-8") if body is not None else None
        return json.loads(self.request(method, url, payload, authenticated=True))

    def find(self, path):
        try:
            return self.api("GET", path)
        except HttpFailure as error:
            if error.status == 404:
                return None
            raise

    def attributes(self, doc_id):
        result, seen = [], set()
        query = {"limit": 100}
        while True:
            page = self.api("GET", f"/documents/{doc_id}/attributes", query=query)
            result.extend(page.get("attributes", []))
            token = page.get("next")
            if not token:
                return result
            if token in seen:
                raise MigrationError("Repeated attribute continuation token; export is incomplete")
            seen.add(token)
            query["next"] = token

    def upload(self, response, record, content):
        if response.get("documentId") != record["documentId"] or not response.get("url"):
            raise MigrationError("Upload response is missing the expected ID or URL")
        headers = dict(response.get("headers") or {})
        if not any(key.lower() == "content-type" for key in headers):
            headers["Content-Type"] = record["contentType"]
        self.request("PUT", response["url"], data=content, headers=headers)


def ensure_definitions(client):
    for key in KEYS:
        existing = client.find("/attributes/" + urllib.parse.quote(key, safe=""))
        if existing is None:
            client.api("POST", "/attributes", {"attribute": {
                "key": key, "dataType": "STRING", "type": "STANDARD"}})
        else:
            definition = existing["attribute"]
            if (definition.get("dataType", "STRING") != "STRING" or
                    definition.get("type", "STANDARD") != "STANDARD"):
                raise MigrationError("An existing sample attribute has an incompatible definition")


def read_metadata(client, record):
    path = "/documents/" + record["documentId"]
    details = client.api("GET", path)
    if details.get("path") != record["path"] or details.get("contentType") != record["contentType"]:
        raise MigrationError("Document path or content type differs; no existing document was overwritten")
    attributes = client.attributes(record["documentId"])
    values = {attribute["key"]: attribute.get("stringValue") for attribute in attributes}
    if any(values.get(key) != value for key, value in record["attributes"].items()):
        raise MigrationError("Sample source/batch attributes differ; reconcile before proceeding")
    return details, attributes


def read_content(client, record):
    download = client.api("GET", "/documents/" + record["documentId"] + "/url")
    if not download.get("url"):
        raise NotReady("Content download URL is not available yet")
    # A separate unauthenticated request: never send the API JWT to the content URL.
    content = client.request("GET", download["url"])
    if len(content) != record["bytes"] or digest(content) != record["sha256"]:
        raise MigrationError("Downloaded content differs from the source; reconcile before proceeding")
    return content


def read_record(client, record):
    details, attributes = read_metadata(client, record)
    return details, attributes, read_content(client, record)


def verify_record(client, record):
    for attempt in range(6):
        try:
            return read_record(client, record)
        except HttpFailure as error:
            if error.status != 404 or attempt == 5:
                raise
        except NotReady:
            if attempt == 5:
                raise
        time.sleep(min(2 ** attempt, 4))
    raise MigrationError("Verification did not complete")


def import_records(directory, client, manifest, manifest_hash, maximum=None):
    state_file = directory / "api-checkpoint.json"
    binding = {"manifestSha256": manifest_hash, "apiUrl": client.base_url, "siteId": client.site_id}
    state = json.loads(state_file.read_text()) if state_file.exists() else {**binding, "records": {}}
    if any(state.get(key) != value for key, value in binding.items()):
        raise MigrationError("Checkpoint belongs to another manifest, API, or site")
    ensure_definitions(client)
    selected = manifest["records"][:maximum] if maximum else manifest["records"]
    for record in selected:
        doc_id = record["documentId"]
        upload = None
        existing = client.find("/documents/" + doc_id)
        prior = state["records"].get(doc_id)
        if existing is None and prior:
            raise MigrationError("Previous create is unresolved or a verified record disappeared; "
                                 "no create was replayed. Reconcile the document ID and checkpoint.")
        if existing is None:
            state["records"][doc_id] = "create-attempted"
            save_json(state_file, state)
            body = {key: record[key] for key in ("documentId", "path", "contentType")}
            body.update({"checksumType": "SHA256", "checksum": record["sha256"],
                         "attributes": [{"key": k, "stringValue": v}
                                        for k, v in record["attributes"].items()]})
            upload = client.api("POST", "/documents/upload", body)
            if upload.get("documentId") != doc_id:
                raise MigrationError("Create returned an unexpected ID; reconcile before proceeding")
            state["records"][doc_id] = "created"
            save_json(state_file, state)
        elif prior in ("create-attempted", "created"):
            # This job created the metadata but never attempted a content write.
            # Reconcile ownership and existing bytes before requesting a fresh URL.
            read_metadata(client, record)
            try:
                read_content(client, record)
            except (HttpFailure, NotReady) as error:
                if isinstance(error, HttpFailure) and error.status != 404:
                    raise
                upload = client.api("GET", f"/documents/{doc_id}/upload", query={
                    "checksumType": "SHA256", "checksum": record["sha256"]})
        if upload is not None:
            content = read_source(directory, record)
            state["records"][doc_id] = "upload-attempted"
            save_json(state_file, state)
            client.upload(upload, record, content)
            state["records"][doc_id] = "uploaded"
            save_json(state_file, state)
        try:
            verify_record(client, record)
        except (HttpFailure, NotReady) as error:
            if ((not isinstance(error, HttpFailure) or error.status == 404) and
                    state["records"].get(doc_id) in ("upload-attempted", "uploaded")):
                raise MigrationError("Previous upload is unresolved or not readable yet; no PUT "
                                     "was replayed. Reconcile storage and processing before retrying.") from None
            raise
        state["records"][doc_id] = "verified"
        save_json(state_file, state)
        print(f"Verified {record['sourceId']} -> {doc_id}")


def export_records(output, client, manifest):
    output.mkdir(parents=True, exist_ok=False)
    exported = []
    for record in manifest["records"]:
        details, attributes, content = verify_record(client, record)
        filename = record["documentId"] + ".bin"
        (output / filename).write_bytes(content)
        exported.append({"sourceId": record["sourceId"], "documentId": record["documentId"],
                         "file": filename, "bytes": len(content), "sha256": digest(content),
                         "document": details, "attributes": attributes, "status": "verified"})
    save_json(output / "manifest.json", {
        "version": 1, "scope": "Prepared sample records only; current content and attributes",
        "apiUrl": client.base_url, "siteId": client.site_id, "batchId": manifest["batchId"],
        "verifiedAt": datetime.now(timezone.utc).isoformat(), "records": exported})
    print(f"Verified and exported {len(exported)} sample records. "
          "Other repository records were not inventoried.")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("command", choices=("prepare", "import", "verify-export"))
    parser.add_argument("--directory", type=Path, default=Path("migration-sample"))
    parser.add_argument("--output", type=Path, default=Path("migration-sample-export"))
    parser.add_argument("--max-records", type=int)
    args = parser.parse_args()
    if args.max_records is not None and args.max_records < 1:
        parser.error("--max-records must be positive")
    try:
        if args.command == "prepare":
            prepare(args.directory)
            return
        manifest, manifest_hash = load_manifest(args.directory)
        client = Client(os.environ.get("FORMKIQ_API_URL", ""),
                        os.environ.get("FORMKIQ_TOKEN", ""), os.environ.get("FORMKIQ_SITE_ID", ""))
        if args.command == "import":
            import_records(args.directory, client, manifest, manifest_hash, args.max_records)
        else:
            export_records(args.output, client, manifest)
    except (MigrationError, OSError, ValueError, KeyError) as error:
        print(f"Stopped: {error}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
