package io.teaql.examples.attachments;

import io.teaql.blob.reference.*;
import io.teaql.blob.store.file.*;
import io.teaql.blob.content.tika.TikaBlobContentVerifier;
import io.teaql.core.*;
import io.teaql.core.blob.*;
import io.teaql.core.meta.*;
import io.teaql.core.sql.*;
import io.teaql.core.view.*;
import io.teaql.dataservice.sql.SqlDataServiceExecutor;
import io.teaql.provider.jdbc.JdbcSqlExecutor;
import io.teaql.runtime.*;
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.security.SecureRandom;
import java.sql.*;
import java.time.*;
import java.util.*;
import java.util.logging.Logger;
import javax.sql.DataSource;

/** Standalone documentation example; the explicit metadata replaces a generated model here. */
public final class AttachmentExample {
    private static final BlobScope SCOPE = new BlobScope("example", "tenant-a");
    public static void main(String[] args) throws Exception {
        Path root = Files.createTempDirectory("teaql-attachment-guide-");
        try { run(root); }
        finally {
            try (var paths = Files.walk(root)) {
                for (var path : paths.sorted(Comparator.reverseOrder()).toList()) Files.deleteIfExists(path);
            }
        }
    }
    private static void run(Path root) throws Exception {
        Clock clock = Clock.systemUTC();
        byte[] signingKey = new byte[32]; new SecureRandom().nextBytes(signingKey);
        var files = new FileBlobStore(root.resolve("objects"));
        try (var database = new OwnedDatabase();
             var gateway = new FileBlobHttpGateway(files, new InetSocketAddress("127.0.0.1", 0),
                 URI.create("http://127.0.0.1:0/blob-read"), "example", Map.of("example", signingKey),
                 clock, Duration.ofMinutes(10))) {
            var sql = database.sql;
            sql.execute("CREATE TABLE asset_data(id BIGINT PRIMARY KEY,version BIGINT NOT NULL,title VARCHAR(100),contract VARCHAR(128),cover VARCHAR(128))");
            var catalog = new PostgresBlobCatalog(sql);
            catalog.migrate(); files.initialize(); gateway.start();
            var scopes = (BlobBindingAuthorization.ScopeProvider) ctx -> ctx.getAttribute("scope", BlobScope.class);
            // This disposable single-actor demo grants its actor access. A host supplies real policies.
            var module = BlobReferenceModule.builder().catalog(catalog).store(gateway).clock(clock)
                .verifier(new TikaBlobContentVerifier(root.resolve("verify"), TikaBlobContentVerifier.Limits.defaults()))
                .bindingAuthorization(new BlobBindingAuthorization(scopes, (ctx,target,kind) -> true, (ctx,target,blob) -> true))
                .uploadAuthorization(new BlobUploadAuthorization(scopes, (ctx,target) -> true, (ctx,target,action,info) -> true))
                .readAuthorization(new BlobReadAuthorization(scopes, (ctx,target) -> true, (ctx,target,blob) -> true))
                .maintenancePermission((ctx,scope) -> false).build();
            try (var runtime = module.installInto(TeaQLRuntime.builder().metadata(metadata())
                    .dataService("default", new SqlDataServiceExecutor("default", sql))
                    .viewAuthorization(viewPolicy()).viewClock(clock)
                    .telemetry(RuntimeTelemetry.NOOP).executionLogging(false)).build()) {
                runtime.install(RuntimeModule.of().withRequiredCapabilities("blob.v1", "view.v1"));
                runtime.validateReadiness();
                var ctx = new DefaultUserContext(runtime);
                ctx.putAttribute("scope", SCOPE); ctx.putAttribute("principal", "demo-user");
                Path pdf = Path.of(required("TEAQL_VIEW_PDF"));
                Path png = Path.of(required("TEAQL_VIEW_PNG"));
                BlobRef contract = upload(ctx, "contract", "contract.pdf", pdf, "contract-upload-1");
                BlobRef cover = upload(ctx, "cover", "cover.png", png, "cover-upload-1");
                System.out.println("PASS upload: PDF contract and PNG cover confirmed");
                var asset = new Asset();
                asset.__internalInitializeNewEntityId(42L);
                asset.updateProperty("title", "Supplier agreement");
                asset.updateProperty("contract", contract);
                asset.updateProperty("cover", cover);
                asset.setComment("Create asset with contract and cover");
                runtime.saveGraph(ctx, asset);
                assertStored(database, contract, cover);
                System.out.println("PASS save: two independent fields persist stable Keys");
                PreparedView prepared = runtime.prepareView(ctx, Map.of("data", asset), ViewOptions.afterCommit());
                var body = (Map<?,?>) ((Map<?,?>) prepared.value()).get("data");
                assertDownload(body.get("contract"), pdf, "application/pdf");
                assertDownload(body.get("cover"), png, "image/png");
                require(contract.equals(asset.contract) && cover.equals(asset.cover));
                System.out.println("PASS read: two complete URLs retrieve original bytes; entity Keys unchanged");
                BlobRef replacement = upload(ctx, "contract", "replacement.pdf", pdf, "contract-upload-2");
                require(!contract.equals(replacement));
                asset.updateProperty("contract", replacement);
                asset.setComment("Replace supplier contract");
                runtime.saveGraph(ctx, asset);
                assertStored(database, replacement, cover);
                System.out.println("PASS replace: new contract Key; cover preserved");
                asset.updateProperty("cover", null);
                asset.setComment("Remove cover attachment");
                runtime.saveGraph(ctx, asset);
                assertStored(database, replacement, null);
                var read = runtime.prepareView(ctx, Map.of("data", asset), ViewOptions.readOnly());
                var readBody = (Map<?,?>) ((Map<?,?>) read.value()).get("data");
                require(readBody.containsKey("cover") && readBody.get("cover") == null);
                assertDownload(readBody.get("contract"), pdf, "application/pdf");
                System.out.println("PASS clear and reread: null cover; contract still downloadable");
                gateway.close();
                try {
                    runtime.prepareView(ctx, asset, ViewOptions.afterCommit());
                    throw new IllegalStateException("Expected signing failure");
                } catch (ViewPreparationException failed) { require(failed.businessCommitted()); }
                assertStored(database, replacement, null);
                System.out.println("PASS committed presentation failure: saved state remains; retry is a read");
            }
        }
    }
    // Public runtime API, reusable in an application-owned upload endpoint.
    private static BlobRef upload(UserContext ctx, String field, String fileName, Path path, String requestId) throws IOException {
        var uploads = ctx.capability(BlobRuntime.class).upload();
        var session = uploads.begin(ctx, new BlobFieldTarget("Asset", null, field),
            new BlobRuntime.Uploads.FileInfo(fileName, Files.size(path), null), requestId);
        try (InputStream content = Files.newInputStream(path)) {
            uploads.write(ctx, session.uploadId(), content);
        }
        return uploads.complete(ctx, session.uploadId());
    }
    private static void assertStored(OwnedDatabase db, BlobRef contract, BlobRef cover) {
        var row = db.independent.queryForList("SELECT contract,cover FROM asset_data WHERE id=42", new Object[0]).get(0);
        require(contract.key().equals(row.get("contract")));
        require(Objects.equals(cover == null ? null : cover.key(), row.get("cover")));
    }
    private static void assertDownload(Object value, Path expected, String mime) throws IOException {
        URI url = URI.create((String) value);
        require(url.isAbsolute());
        var connection = (HttpURLConnection) url.toURL().openConnection();
        connection.setConnectTimeout(5000); connection.setReadTimeout(5000);
        try (var stream = connection.getInputStream()) {
            require(Arrays.equals(Files.readAllBytes(expected), stream.readAllBytes()));
            require(mime.equals(connection.getContentType()));
        } finally { connection.disconnect(); }
    }
    private static EntityMetaFactory metadata() {
        var metadata = new SimpleEntityMetaFactory();
        var descriptor = new SQLEntityDescriptor();
        descriptor.setType("Asset"); descriptor.setTargetType(Asset.class); descriptor.setEntitySupplier(Asset::new);
        ((GenericSQLProperty) descriptor.addSimpleProperty("id", Long.class)).setColumnType("BIGINT");
        ((GenericSQLProperty) descriptor.addSimpleProperty("version", Long.class)).setColumnType("BIGINT");
        ((GenericSQLProperty) descriptor.addSimpleProperty("title", String.class)).setColumnType("VARCHAR(100)");
        for (String field : List.of("contract", "cover")) {
            var property = (BlobSQLProperty) descriptor.addSimpleProperty(field, BlobRef.class, BlobSQLProperty::new);
            property.setTableName("asset_data"); property.setColumnType("VARCHAR(128)");
            property.withBlobFieldSpec(BlobFieldSpec.of("Asset", field,
                List.of(field.equals("contract") ? "pdf" : "png"), true, "default"));
        }
        metadata.register(descriptor); return metadata;
    }
    private static ViewAuthorization viewPolicy() {
        return new ViewAuthorization() {
            @Override public Identity identity(UserContext ctx) {
                var scope = ctx.getAttribute("scope", BlobScope.class);
                return new Identity(scope.realm(), ctx.getAttribute("principal", String.class), scope.boundary());
            }
            @Override public boolean canReadEntity(UserContext ctx, EntityTarget target, String path) { return true; }
            @Override public FieldDecision field(UserContext ctx, EntityTarget target, String field, String path, ViewOptions.Mode mode) { return FieldDecision.show(); }
        };
    }
    private static void require(boolean condition) { if (!condition) throw new IllegalStateException("Attachment example assertion failed"); }
    private static String required(String name) {
        String value = System.getenv(name);
        if (value == null || value.isBlank()) throw new IllegalStateException("Missing configuration: " + name);
        return value;
    }
    public static final class Asset extends BaseEntity {
        private BlobRef contract, cover;
        private String title;
        @Override public String typeName() { return "Asset"; }
        @Override public void __internalSet(String field, Object value) {
            switch (field) {
                case "contract" -> { contract = (BlobRef) value; markPropertyLoaded(field); }
                case "cover" -> { cover = (BlobRef) value; markPropertyLoaded(field); }
                case "title" -> { title = (String) value; markPropertyLoaded(field); }
                default -> super.__internalSet(field, value);
            }
        }
        @Override public Object __internalGet(String field) {
            return switch (field) { case "contract" -> contract; case "cover" -> cover; case "title" -> title; default -> super.__internalGet(field); };
        }
    }
    private static final class OwnedDatabase implements AutoCloseable {
        final String schema="r4_view_cli_"+UUID.randomUUID().toString().replace("-","");
        final String url=required("TEAQL_BLOB_TEST_PG_URL"),user=required("TEAQL_BLOB_TEST_PG_USER"),password=required("TEAQL_BLOB_TEST_PG_PASSWORD");
        final JdbcSqlExecutor sql,independent;
        OwnedDatabase() throws SQLException {
            try (Connection connection=DriverManager.getConnection(url,user,password); Statement statement=connection.createStatement()) { statement.execute("CREATE SCHEMA "+schema); }
            var source=new DataSource() {
                @Override public Connection getConnection() throws SQLException {
                    Connection connection=DriverManager.getConnection(url,user,password);
                    try (Statement statement=connection.createStatement()) { statement.execute("SET search_path TO "+schema); statement.execute("SET lock_timeout='5s'"); statement.execute("SET statement_timeout='10s'"); }
                    catch (SQLException failed) { connection.close(); throw failed; } return connection;
                }
                @Override public Connection getConnection(String user,String password) throws SQLException { throw new SQLFeatureNotSupportedException(); }
                @Override public PrintWriter getLogWriter() { return null; }
                @Override public void setLogWriter(PrintWriter writer) {}
                @Override public void setLoginTimeout(int seconds) {}
                @Override public int getLoginTimeout() { return 0; }
                @Override public Logger getParentLogger() { return Logger.getLogger("teaql.example.blobview"); }
                @Override public <T> T unwrap(Class<T> type) throws SQLException { throw new SQLFeatureNotSupportedException(); }
                @Override public boolean isWrapperFor(Class<?> type) { return false; }
            };
            sql=new JdbcSqlExecutor(source); independent=new JdbcSqlExecutor(source);
        }
        @Override public void close() throws SQLException { try (Connection connection=DriverManager.getConnection(url,user,password); Statement statement=connection.createStatement()) { statement.execute("DROP SCHEMA "+schema+" CASCADE"); } }
    }
}
